简体   繁体   中英

dynamically created list item onclick

I am completely new to HTML and JavaScript and I am completely lost.

I am trying to create a to do list where input adds to the top of the list, and when an item in the list is clicked, it is removed.

I am trying to avoid using JQuery or anything outside of pure js.

<!DOCTYPE html>
<html>

<script type="text/JavaScript">

var number_of_items = 0;
var list = [];
var list_container = document.createElement("div");
list_container.id = "container"; 

function makelist(){
    list_container.innerHTML = "";

    list.unshift(document.getElementById("todo").value);

    ++number_of_items;

    document.getElementsByTagName("body")[0].appendChild(list_container);
    var list_element = document.createElement("ul");
    list_container.appendChild(list_element);

    for( var i=0 ; i < number_of_items ; ++i){
           var list_item = document.createElement("li");
               list_item.innerHTML = list[i];

           //The problem is here
           list_item.onClick = function(){

                alert("working");
                list.splice(i, 1);
                --number_of_items;
                makelist();

           }

           list_element.appendChild(list_item);
    }
}

</script>

<body>
Todo: <input type="text" id="todo">

<input type="button" value="Submit" onclick="makelist()" />



</body>
</html>

The problem is, the list_item onclick function never activates. Why?

I apologize in advance for any problems with the way I stated my question.

http://jsbin.com/wicopu/1/edit

use onclick instead of onClick ...

or even better ... use event listeners

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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