问题
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"
Here's what I've done: http://jsfiddle.net/VvLXk/2/
But it's not working.
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.
What is wrong with my code? Javascript / JQuery solutions are welcome.
回答1:
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;
}
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.
}
}
Modified fiddle: http://jsfiddle.net/jLLHH/ (note: logs rather than redirecting)
回答2:
This question has been answered here : How to use getElementsByClassName in javascript-function?
http://jsfiddle.net/VvLXk/9/ here is a sample of it working :
var dropdown = document.getElementsByClassName("page-dropdown")[0];
function onCatChange()
{
if ( dropdown.options[dropdown.selectedIndex].value > 0 )
{
location.href = "http://www.example.com/?page_id="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
回答3:
What you are selecting will return array, please try this:
var dropdown = document.getElementsByClassName("page-dropdown");
function onCatChange()
{
alert(dropdown[0]);
if ( dropdown[0].options[dropdown[0].selectedIndex].value > 0 )
{
window.location.href = "http://www.example.com/?page_id="+dropdown[0].options[dropdown[0].selectedIndex].value;
}
}
dropdown[0].onchange = onCatChange;
Hope this helps.. Cheers !!
来源:https://stackoverflow.com/questions/24292561/javascript-getelementsbyclassname-not-working-with-select