调用以下脚本可以动态添加html输入元素。下面的标记代码(大约30行)有两个问题。
1)当我在第二个输入框(foox1-“ last name”)下方添加标记的代码时,应显示两个输入框(foox1-“ last name”)。
2)其二是我需要id ='uggestions'来动态化,即链接到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'> </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>
您不能.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'> </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'> </div> </div>";
编辑:对于您的问题的第二部分,您可以id='suggestions_for_' + fooId + x + i
在上述声明中进行。(它会产生类似的东西id='suggestions_for_foo11'
。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句