如何使JavaScript创建的列表项可单击?

时间:2017-08-14 14:22:26

标签: javascript html html-lists

我一直在处理所有相关问题,但没有一个解决方案适合我。我对JavaScript非常陌生,我很困惑如何使用JavaScript创建的列表具有可点击的项目。最近的尝试包括尝试在点击时弹出警报,但它只是弹出第二个页面加载。请帮忙!这是我目前的代码:

<!DOCTYPE html>
<html>
<head>
 <link rel="stylesheet" href="css/m-buttons.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
div.links{
margin: auto;
 border: 3px solid #003366;
text-align: left;
max-width: 700px;
}
p{
font-size: 40px;
text-align: center;
}
li{
font-size: 1w;
}
body{
font-family: verdana;
}
</style>
</head>
<body>
<div class = "links">
<ul id="blah"></ul>
<script>
var testArray = ["One","Two","Three","Four","Five","Six","Seven"];
function makeLongArray(array){
for(var i = 0; i < 1000; i++){
array.push(i);
}
}
makeLongArray(testArray);
function makeUL(array) {
    // Create the list element:
    var list = document.createElement("UL");
    list.setAttribute("id", "blah");

    for(var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement("LI");

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
        list.onclick = alert("Help."); //this is the code causing the issue.
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById("blah").appendChild(makeUL(testArray));
</script>
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

每次执行此行代码alert('Help.')时,您的现有代码都会执行list.onclick = alert("Help.");

您需要做的是为onclick分配一个功能。然后在执行onclick时执行此功能。如下:

item.onclick = function() {console.log('hello world');};

现在每个列表项的onclick事件都有一个分配给它的函数,每次单击列表项时都会向控制台输出 hello world

答案 1 :(得分:1)

您需要为onclick事件指定一个函数:

list.onclick = function(){ alert("Help."); }

答案 2 :(得分:0)

这是我的解决方案:

function toggleDone(event) {
  var ev = event.target;
  ev.classList.toggle("done");
}

ul.addEventListener("click", toggleDone);