Javascript Dynamic GetElementByID

Javascript Dynamic GetElementByID

本文关键字:GetElementByID Dynamic Javascript      更新时间:2023-09-26

我想在两个不同的元素上使用相同的函数,而无需复制我的代码并更改 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)
        }

有什么想法吗?

在我看来

,错误似乎在其他地方,具体在这一行中:

selected[count] = selObj.options.value;

那不应该是:

selected[count] = selObj.options[x].value;

或(不需要额外的"计数"变量)

selected.push( selObj.options[x].value );

(此外,你在x = 0前面缺少一个var,从而使x成为全局变量。