addEventListener working in firefox but not in chrome

懵懂的女人 提交于 2020-01-04 01:46:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!