0

尽管这段代码确实有效,但我试图将其缩小为一个循环......到目前为止,我所有的尝试都失败了。您将看到四个具有不同 ID 的下拉列表......但是,它们确实具有相同的类名(optionLinks)。这是代码:

function init(){

    var allE = document.getElementById("executive");
    allE.onchange = loadLink;

    var allL = document.getElementById("legislative");
    allL.onchange = loadLink;

    var allJ = document.getElementById("judicial");
    allJ.onchange = loadLink;

    var allS = document.getElementById("state");
    allS.onchange = loadLink;
}

感谢大家 :)

4

3 回答 3

1

使用适度更新的浏览器:

[].forEach.call(document.querySelectorAll('.optionLinks'), function(a){
    a.addEventListener('change', loadLink);
});

JS 小提琴演示

参考:

于 2013-10-27T00:17:11.687 回答
0
var ids = ['executive','legislative','judicial','state'];
for (var i = 0; i < ids.length; i++)
    document.getElementById(ids[i]).onChange = loadLink;

或者...

var elements = document.getElementsByClassName('optionLinks');
for (var i = 0; i < elements.length; i++)
    elements[i].onChange = loadLink;
于 2013-10-27T00:14:09.873 回答
0
elements = document.getElementsByClassName('optionLinks');
for (var i = 0; i < elements.length; i++) {
    elements[i].onchange = loadLink;
}
于 2013-10-27T00:15:28.197 回答