繁体   English   中英

了解onclick以及如何将其添加到li中

[英]Understanding onclick and how to add it to li's

所以我使用JS(只有JS)来创建一个li的列表,其中包含存储在a中的对象。

当我点击li时,我希望更新相应的分数,但我似乎不了解JS如何创建元素。

var a = []; //I have a global array variable housing all different objects
function getChants() { //this function is not really important for the question at hand, I just wanted to show createListofLis is called in it
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        //document.getElementById("demo").innerHTML =
        //this.getResponseHeader("Last-Modified");
        a = JSON.parse(this.responseText);
        console.log(a);
        createListofLis();
    }
}   
xhttp.open("GET", "chants.json", true);
xhttp.send();
}

function createListofLis(){ 
d = document.getElementById('outscreen')
while (d.firstChild) { //have to clear the ul completely before adding to it once again. this is probably inefficient, just trying to get a working solution
    d.removeChild(d.firstChild);
}
for (chant in a){ 
    node = document.createElement("LI");
    node.onclick = updateScore(node.innerHTML.substring(0, node.innerHTML.indexOf('-')));                        // Append the text to <li>. trouble part of code
    snippet = a[chant].chant + "---->" + a[chant].score + "\n";
    console.log(snippet);
    textnode = document.createTextNode(snippet);
    node.appendChild(textnode);      
    d.appendChild(node);
}
};

function updateScore(chant){ //this is what's supposed to update the objects score value

//a[chant].score += 1; //i have this commented out because it keeps giving me a reference error saying that score is undefined, i would like this to be where the score is updated based on clicking the li
console.log(chant);};

所以基本上当我运行createListofLis函数代码时:

node.onclick = updateScore(node.innerHTML.substring(0, node.innerHTML.indexOf('-')));                        // Append the relevant text to <li>

我希望updateScore不会运行。 我希望li具有onclick属性,其中li的innerHTML值找到相关分数并将其加1。 我不明白为什么这不起作用 - 当我打开控制台并查看元素时,我没有看到绑定到每个li元素的onclick属性。 相反,只要运行createListofLis,该函数就会运行。

顺便说一下,我是JS的新手,所以要善待:)。

这段代码:

node.onclick = updateScore(node.innerHTML.substring(0, node.innerHTML.indexOf('-')));

导致立即调用updateScore函数,将其返回值(即undefined )分配给onlick处理程序,因此不添加实际处理程序。

替换为:

node.onclick = function() {
  updateScore(node.innerHTML.substring(0, node.innerHTML.indexOf('-')));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM