函数没有被"点击"的addEventListener

时间:2015-11-06 16:04:43

标签: javascript

这是我的代码,它将事件监听器附加到具有var标记的所有元素,然后触发一个名为getWords()的函数

//The local database
wordBank = [
            // {word:"aprobi", translation:"to approve", count:2},
            // {word:"bati", translation:"to hit, to beat, to strike", count:1},
            // {word:"da", translation:"of", count:1}
            ];

//getting the var tags and attaching the event listeners
var wordsWritten = document.getElementsByTagName("var");

for (var i = 0; i < wordsWritten.length; i++){
    wordsWritten[i].addEventListener("click", getWords())
};

//Getting the details from the word
function getWords() {
    if (document.getElementsByClassName("vortarobobelo").length != 0){
        var words;
        words = document.getElementsByClassName("vortarobobelo")[0].children[0].children;

        for (var i =0; i < words.length; i++) {
            var localBank = {} //creating the local variable to store the word
            var newWord = words[i].children[0].innerText; // getting the word from the DOM
            var newTranslation = words[i].children[1].innerText; // getting the translation from the DOM

            localBank.word = newWord;
            localBank.translation = newTranslation;
            localBank.count = 0 //assuming this is the first time the user has clicked on the word

            console.log(localBank);
            wordBank.push(localBank);
            // fireBank.update(wordBank);
        }
    }
}

如果我在使用for循环来附加事件过程时我只是放了整个getWords()函数,它就可以了。但我不明白为什么这种方式不起作用。< / p> P.S:有没有更好的方法来分解我的代码?

1 个答案:

答案 0 :(得分:5)

这一行

wordsWritten[i].addEventListener("click", getWords())

应该是

wordsWritten[i].addEventListener("click", getWords)

即传递引用函数而不是调用函数

的结果
相关问题