2015-11-06 101 views
0

这里是我的代码,它附加一个事件侦听器,用var标记的所有元素,然后触发一个函数调用getWords()功能没有被触发的“点击”的addEventListener

//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); 
     } 
    } 
} 

它的工作原理只是很好,如果我只是把整个getWords()函数,当我使用for循环附加eventlisteners,但我不明白为什么这种方式不起作用。

P.S:有更好的方法来分解我的代码吗?

回答

4

此行

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

应该是

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

即传递参照功能不调用函数的结果