javascript getElementsByClassName无法与< select> [英] javascript getElementsByClassName not working with <select>
问题描述
我正在尝试使用getElementsByClassName使我选择的选项根据值跳到其URL:
I am trying to use getElementsByClassName to make my select's options jump to their URL's depending on the value:
http://www.example.com/?page_id="value"
这就是我所做的: http://jsfiddle.net/VvLXk/2/
但是它不起作用.
我知道我可以使用getElementByID,但是我有三个选择元素(并且我可能会添加更多元素).我认为这仅适用于一个要素.出于这个原因,我求助于getElementsByClassName不能正常工作.
I know I can use the getElementByID but I have three select elements (and I might add more). I believe it only applies to one element. And for that reason I have resorted to getElementsByClassName which is not working.
我的代码有什么问题?欢迎使用Javascript/JQuery解决方案.
What is wrong with my code? Javascript / JQuery solutions are welcome.
推荐答案
As discussed in How to use getElementsByClassName in javascript-function?, getElementsByClassName()
provides a collection of elements. To assign an event handler, you'll have to iterate over it and modify each individual element.
for (var i = 0, l = dropdown.length; i < l; i++) {
dropdown[i].onchange = onCatChange;
}
除此之外,您还可以引用处理程序function
中使用this
触发事件的单个dropdown
.
Along with that, you can then reference the single dropdown
that the event was triggered for with this
inside the handler function
.
function onCatChange() {
if ( this.options[this.selectedIndex].value > 0 ) {
// etc.
}
}
修改过的小提琴: http://jsfiddle.net/jLLHH/(注意:日志而非重定向)
Modified fiddle: http://jsfiddle.net/jLLHH/ (note: logs rather than redirecting)
这篇关于javascript getElementsByClassName无法与< select>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!