我有一个表单,用户可以在其中为多个城市添加多个选择框。问题在于,每个新生成的选择框都需要具有唯一的ID。可以通过JavaScript完成吗?
更新:这是选择城市的表格的一部分。另外请注意,我使用一些PHP当选择一个特定的状态,以填补城市。
<form id="form" name="form" method="post" action="citySelect.php">
<select id="state" name="state" onchange="getCity()">
<option></option>
<option value="1">cali</option>
<option value="2">arizona</option>
<option value="3">texas</option>
</select>
<select id="city" name="city" style="width:100px">
</select>
<br/>
</form>
这是JavaScript:
$("#bt").click(function() {
$("#form").append(
"<select id='state' name='state' onchange='getCity()'>
<option></option>
<option value='1'>cali</option>
<option value='2'>arizona</option>
<option value='3'>texas</option>
</select>
<select id='city' name='city' style='width:100px'></select><br/>"
);
});
你不仅可以保持运行中的索引吗?
var _selectIndex = 0;
...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
编辑
经过进一步考虑,你实际上可能更喜欢对选择使用数组样式的名称。
例如
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
然后,例如在php的服务器端:
$cities = $_POST['city']; //array of option values from selects
编辑2回应OP评论
可以使用DOM方法动态创建选项,如下所示:
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
var city = null,city_opt=null;
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
var city_opt = document.createElement("option");
city_opt.setAttribute("value",city);
city_opt.appendChild(document.createTextNode(city));
newSelectBox.appendChild(city_opt);
}
document.getElementById("example_element").appendChild(newSelectBox);
假设cities
数组已经存在
或者,你可以使用innerHTML方法.....
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
document.getElementById("example_element").appendChild(newSelectBox);
var city = null,htmlStr="";
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
htmlStr += "<option value='" + city + "'>" + city + "</option>";
}
newSelectBox.innerHTML = htmlStr;
如何将<option> </ option>标记与此插入?
请注意,使用运行计数器可能会导致页面命中之间极有可能发生冲突。换句话说,如果每次页面加载时计数器都从1开始,那么下一次编辑/更新对象时您可能会发生冲突。记住这一点很好。