我有从包含类别节点的xml读取的javascript代码,并使用它填充下拉列表。每次用户创建新产品列表时,都会创建该类别节点。但是,这意味着当读取xml时,类别会填充相机,相机,相机,其他等项目。如何删除或有不同的选项?
function loadXMLcat()
{
var xmlhttp=false;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","auction.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var category;
var str;
var i;
var j;
str=("<p>Category : <select onchange=\"reveal(this)\" name=category>");
var x=xmlDoc.getElementsByTagName("Product");
if(x.length>0)
{
for (i=0;i<x.length;i++)
{
category=xmlDoc.getElementsByTagName("Category");
str+="<option value=" + category[i].childNodes[0].nodeValue + ">" + category[i].childNodes[0].nodeValue + "</option>"
/**var arr = category;
var sorted_arr = arr.sort()
var results = [];
for (var i = 0; i < arr.length - 1; i++)
{
if (sorted_arr[i + 1] !== sorted_arr[i])
{
str+="<option value=" + arr[i] + ">" + arr[i] + "</option>"
str+="<option value=" + sorted_arr[i] + ">" + sorted_arr[i] + "</option>"
}
}**/
}
str+="<option id=\"others\" value=\"Other\">Other</option>";
}
else
str+="<option id=\"others\" value=\"Other\">Other</option>";
str+=("</select></p>");
document.getElementById('category').innerHTML=str;
}
答案 0 :(得分:0)
这是一个相同的循环,检查该类别是否已添加到选择框中。我还添加了contains()函数来快速测试重复项。
function loadXMLcat()
{
var xmlhttp=false;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","auction.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var str;
var i;
var j;
str=("<p>Category : <select onchange=\"reveal(this)\" name=category>");
var categoryList= []; //Array to contains the distinct values
var x=xmlDoc.getElementsByTagName("Product");
var categories = xmlDoc.getElementsByTagName("Category");
if(x.length>0)
{
for (i=0;i<x.length;i++)
{
var category=categories[i].childNodes[0].nodeValue;
var currentOption ="<option value=" + category + ">" + category + "</option>";
//Verify is category has already be added
if(!contains(categoryList,category)){
categoryList.push(category);
str += currentOption;
}
}
str+="<option id=\"others\" value=\"Other\">Other</option>";
}
else
str+="<option id=\"others\" value=\"Other\">Other</option>";
str+=("</select></p>");
document.getElementById('category').innerHTML=str;
}
//Utility function to quickly verify if an array contains an element.
function contains(arr, x) {
return arr.filter(function(elem) { return elem == x }).length > 0;
}