Jquery click function is not working for dynamic elements

前端 未结 4 792
借酒劲吻你
借酒劲吻你 2020-12-02 01:55

I am using $.each to create the button with each array object. I also tried to give each button a specific id, so I can do click event for further coding, but n

4条回答
  •  遥遥无期
    2020-12-02 02:37

    The click() function you can call on the elements which have direct binding. Direct binding will only attach event handler which are present at the time of DOM loading i.e. static elements.

    If there are elements created after DOM is loaded, then not all the events associated with them would be triggered if you have not attached the event handlers correctly.

    And when you create dynamic elements that means they are being created after DOM is loaded and they were not present at the time of direct binding, so you can not call directly click() on that.

    if you want to get click functionality on dynamic created elements, you'll have create a delegated binding by using on. This you can achieve by adding a .on handler to a static parent element.

    Delegated events have the advantage that they can process events from descendant elements that          
    are added to the document at a later time.
    

    Change this line

    $("#questlist_item_button_reward" + obj.questid).click(function() {
        alert("reward");
    });
    

    to

    $("#call_questitem").on("click", "#questlist_item_button_reward" + obj.questid, function() {
        alert("reward");
    });
    

    And do the same for the go button as well.

    DEMO

提交回复
热议问题