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:有更好的方法來分解我的代碼嗎?