问题
The given code works in Mozilla Firefox 31.0 but not in Google Chrome 38.0.2125.104 How can this issue be solved?
Please Note : Using the change() function or jQuery is not an option here!
<body>
<select id="category">
<option value="movies">Movies</option>
<option value="artist">Artists</option>
<option value="authors">Authors</option>
<option value="chemistry">Chemistry</option>
</select>
</body>
<script>
window.onload = initialise;
function initialise() {
var options = document.getElementsByTagName('option');
for (var i = 0; i < options.length; i++) {
options[i].addEventListener("click", getQuestion, false);
//console.log(i);
}
}
function getQuestion() {
console.log("getting question..");
}
</script>
</html>
回答1:
I don't know why they all aren't binding but aren't you look for the on change function? So you can just bind to that once?
//Untested
var Category = document.getElementsById('category');
Category.addEventListener("change", getQuestion, false);
Also, If you're not against Jquery, you might want to look into it it often gets rid of cross-browser issues. In Jquery:
$('body').on('change', '#category', function() {
getQuestion($(this));
})
回答2:
try this:
<script>
window.onload = initialise();
function getQuestion() {
console.log("getting question..");
}
function initialise() {
var Category = document.getElementById('category');
Category.addEventListener("change", getQuestion, false);
}
</script>
来源:https://stackoverflow.com/questions/26550550/addeventlistener-working-in-firefox-but-not-in-chrome