我想在两个不同的元素上使用相同的函数,而不重复我的代码和更改id。我想将ID作为参数传递给我的函数,但它不起作用。
function getSelected(id){
var selected = new Array();
**var selObj = document.getElementById(id);** //The problem is here
var count = 0;
for (x=0; x<selObj.options.length; x++){
if (selObj.options[x].selected){
selected[count] = selObj.options.value;
count++;
}
}
alert(count)
}
有什么想法吗?
答案 0 :(得分:1)
向我看,好像错误在其他地方,特别是在这一行:
selected[count] = selObj.options.value;
不应该是:
selected[count] = selObj.options[x].value;
或(无需额外的“计数”变量)
selected.push( selObj.options[x].value );
(此外,您在var
前面缺少x = 0
,从而使x成为全局变量。)