Dynamic li record with jquery. The item cannot be pressed after recording.

I have a function which, when the checkbox is checked, dynamically writes li to ol, which is empty.

the code:

$(":checkbox").click(function() {
    var checkedState = $(this).is(':checked');
    if (checkedState == true) {
       var productName = $(this).attr("title");
       $("#selectedProductsList").append("<li class=\"productList " + this + "\"><p class=\"removeIcon\"><img src=\"images/remove-icon.png\" alt=\"Remove Product\" /></p><span class=\"productName\">"+ productName +"</span></li>");
    };
});

Then, when it is being recorded, a delete icon appears, which removes the element from ol when pressed. This removal icon has a removeIcon class, which can be seen in dynamic above.

I have a function that processes the remove call and then performs some actions: Code:

$('.removeIcon').click(function() {
 alert("starting");
});

Right now I have a remove action just trying to alert the message that it triggered. But it does not seem to be part of the function.

- , li , .click? : DOM $.click()

.live vs .click, .

?

+3
4

...

$(".removeIcon").live("click", function () {
    alert("starting");
}
+2

live() ($(":checkbox").live('click', ...)), click() , .

+1

.delegate() live().

$('#selectedProductsList').delegate('.removeIcon','click',function() {
   alert("starting");
});

.live(), , , , .

+1

If you have an idea, why don’t you let the button into the object? here is a small example (DIDN’T TEST him for helping you in theory, but should work)

$(":checkbox").click(function() {
    var checkedState = $(this).is(':checked');
    if (checkedState == true) {
       var productName = $(this).attr("title");
       var product = $('<li class="productList"><span class="productName">'+ productName +'</span></li>"'); // create a object off the product
       var removeButton = $('<p class="removeIcon"><img src="images/remove-icon.png" alt="Remove Product" /></p>'); // create a object off the image aswell
       // now i can add a event to the object 'removeButton', in the same way what u did earlier(like $('.removeIcon'))
       removeButton.bind('click', function() {
            alert("This click function works");
       });

       // now add the remove button in front off the <span class="productName">
       // im using prepend because that function adds HTML in front off the object
       // append adds HTML at the end.

       product.prepend(removeButton);


       // put the product in your HTML
       $("#selectedProductsList").append(product);
    };
});
0
source

Source: https://habr.com/ru/post/1783239/


All Articles