2013-09-01 42 views
1

下面的腳本被要求動態添加HTML輸入元素。 有與所述標記的代碼的下方(約30線)的兩個問題。使用JavaScript來添加HTML DIV與動感的元素髮出

1)兩個輸入盒裝應顯示,當我添加下面的第二個輸入框標記代碼(foox1 - 「姓」)不被顯示。

2)第二個是,我需要ID =「建議」是動態的,即連接到foox1。我應該像使用setAttribute一樣使用代碼的其餘部分,但是我需要首先獲取1)以上的代碼。

<script language="javascript"> 

var x = 1; 

function add() { 
var fooId = "foo"; 

for (i=1; i<=2; i++) 
    { 
    //Create an input type dynamically. 
    var element = document.createElement("input"); 

    //Assign different attributes to the element. 
    element.setAttribute("type", fooId+x+i); 
    element.setAttribute("name", fooId+x+i); 
    element.setAttribute("id", fooId+x+i); 

    if(i==1){ 
      element.setAttribute("value", "First name"); 
      element.setAttribute("onkeyup", "lookup(this.value);"); 
      element.setAttribute("onblur", "fill();"); 

    } 
    if(i==2){ 
      element.setAttribute("value", "Last name"); 

    } 
    var foo = document.getElementById("fooBar"); 
    foo.appendChild(element); 

    /************************************************ 
    This is where the problem is, in this if statement. 
    This part of the code is required for an autofil in the text box 

    ************************************************/ 

    if(i==1){ 
     foo.appendChild("<div class='suggestionsBox' id='suggestions' style='display: 
      none;'><img src='upArrow.png' style='position: relative; top: -12px; left: 30px;'   
      alt='upArrow' /><div class='suggestionList' id='autoSuggestionsList'>&nbsp;  </div> </div>"); 
    } 

    /******************************** 
    end of code with issues 
    ******************************/ 

    var space = document.createTextNode(" "); 
    foo.appendChild(space); 

} 
     i++;    
      var element = document.createElement("input"); 
    element.setAttribute("type", "button"); 
    element.setAttribute("value", "Remove"); 
    element.setAttribute("id", fooId+x+i); 
    element.setAttribute("name", fooId+x+i);  
    element.setAttribute("onclick", "removeRow(this)"); 
    foo.appendChild(element); 

    var br = document.createElement("br"); 
    foo.appendChild(br); 

    x++; 

} 
</SCRIPT> 
+2

請添加的jsfiddle例子 –

回答

1

你不能在以下環境中使用.appendChild.appendChild添加節點而不是字符串。

foo.appendChild("<div class='suggestionsBox' id='suggestions' style='display: 
      none;'><img src='upArrow.png' style='position: relative; top: -12px; left: 30px;'   
      alt='upArrow' /><div class='suggestionList' id='autoSuggestionsList'>&nbsp;  </div> </div>"); 

它必須是

foo.innerHTML += "<div class='suggestionsBox' id='suggestions' style='display: none;'><img src='upArrow.png' style='position: relative; top: -12px; left: 30px;' alt='upArrow' /><div class='suggestionList' id='autoSuggestionsList'>&nbsp; </div> </div>"; 

Working Demo

編輯:對於你的問題的第二部分,你可以在上面提到的聲明做id='suggestions_for_' + fooId + x + i。 (它會產生類似id='suggestions_for_foo11'

0

你需要結束各自的前兩行與" +