0
Can someone explain why the click function code for the remove button had to be coded inside the add button function?
To do list lesson code for jQuery below. Why is the remove button click code inside the add button click function? $(function() { $("#add").on("click", function() { var val = $("input").val(); if(val !== '') { var elem = $("<li></li>").text(val); $(elem).append("<button class='rem'>X</button>"); $("#mylist").append(elem); $("input").val(""); $(".rem").on("click", function() { $(this).parent().remove(); }); } }); });
1 Odpowiedź
0
The "add" button is given the "click" function, but this function is just waiting for the button to be clicked... i.e. the function is not called at first.
The "click" function will only be called when the user clicks the button.
When add is clicked, the function does the following steps:
1. It creates a todo list item ("elem"),
2. the list item is given its own "rem" button ("X"),
3. the X button is given its own function (i.e. for this one item and no other) to remove the list item.
All these steps have to be done together so that each list item has its own remove.
Therefore, the code inside the add is just an example of how you make sure all related steps are done in the one place where the action/event is triggered.
Hope this long winded explanation is somehow clear.