Warm tip: This article is reproduced from serverfault.com, please click

html-使用javascript创建唯一的ID

(html - create unique id with javascript)

发布于 2010-07-12 19:12:12

我有一个表单,用户可以在其中为多个城市添加多个选择框。问题在于,每个新生成的选择框都需要具有唯一的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/>"
     );
});
Questioner
JamesTBennett
Viewed
11
Jonathan Fingland 2010-07-13 11:09:17

你不仅可以保持运行中的索引吗?

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;