【发布时间】:2016-03-16 18:56:46
【问题描述】:
在我的表单中,我想提供添加另一个位置的功能。当我只出现一个文本框(地址)并且可以显示多个地址文本框时,它正在工作。但现在我正在尝试添加“城市”文本框,但它不起作用。我以前使用一个函数,现在我拆分函数以更好地重用代码。所以现在我的 id (id_) 应该是 id_1,id_2,ect。但我得到的是对象。我认为 addLoc() 应该是独立的,与 function addLoc() 内的 function city() 相比,但这也不起作用。
HTML
<div class="one">
<button onclick="addLoc()">Add Location</button>
</div>
<div class="three">
<h2>Locations</h2>
<form action="#" id="mainform" method="get" name="mainform">
<div id="myForm"></div>
<input type="submit" value="Submit">
</form>
</div>
javaScript
var i = 0;
function increment(){
i += 1;
}
function addLoc(){
var d = document.createElement("DIV");
var l = document.createElement("LABEL");
var i = document.createElement("INPUT");
address();
city();
function address() {
i.setAttribute("type","text");
i.setAttribute("placeholder","Address");
build();
}
function build() {
var g = document.createElement("IMG");
g.setAttribute("src", "delete.png");
increment();
i.setAttribute("Name","textelement_" + i);
d.appendChild(l);
l.setAttribute("for","textelement_" + i);
g.setAttribute("onclick", "removeElement('myForm','id_" + i + "')");
d.appendChild(g);
d.setAttribute("id","id_" + i);
document.getElementById("myForm").appendChild(d);
}
function city() {
i.setAttribute("type","text");
i.setAttribute("placeholder","City");
build();
}
}//end of addLoc()
这里是jsFiddle(一些变化)
仅使用地址文本框就可以正常工作。我打破了一些试图拆分功能的东西。我可以将这一切作为一个 BIG 功能来完成,但我不想这样做。 任何帮助非常感谢!
【问题讨论】:
标签: javascript forms function dynamic