我有一个脚本,它将 li 元素添加到 ul 并根据用户在 select 元素中的选择为其分配一些属性。但是,我认为有必要确保 li 元素不存在于 ul 中。但是,我不确定,但我认为要么数组没有为它分配变量,要么我比较数组的 if 语句有问题。当然,我可能完全不在了。我难住了。
function anotherCounty(){
var newCounty = document.forms['newForm'].county.value;
var ul = document.getElementById("counties");
var items = ul.getElementsByTagName("li");
var itemArray = new Array();
for (var i = 0; i < items.length; i++){
itemArray.push(items[i]);
}
if (itemArray.indexOf(newCounty)<'0'){//I've also tried ==-1 and <0
var new_item = document.createElement("li");
new_item.id = "addCounty[]";
new_item.innerHTML = newCounty;
ul.insertBefore(new_item, ul.firstChild);
}
}