jQuery .on Click second time not working

限于喜欢 提交于 2019-12-12 09:20:20

问题


var elms = $('.selector', list);
elms.off();
elms.on('vclick', function(event, ui) {
        event.preventDefault();
        var elm = $(this);
        customEventHandler(elm, elm.attr("id"));
});

If I bind the click event via $('.selector', list).on('click',...) to an element in a list, it is working fine.

If I add elements after doing .append() to the list and calling again $('.selector', list).on('click',...) no click is triggered. Even if I use .off() before to remove old events.

Any ideas or suggestions?


回答1:


Try this way:- Fiddle

$('.container').on('click', '.selector', function(event, ui) {
        event.preventDefault();
        var elm = $(this);
        alert(elm.index());
});

You can achieve this using delegated events approach.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.




回答2:


Finally found the problem, I had to bind the events after calling list.trigger("create"); instead of before, maybe this is helpful for anyone...




回答3:


Replace c.onclick with 'click'. Use the right format.

$('.container').on('click', '.selector', function(event, ui) {
    event.preventDefault();
    var elm = $(this);
    alert(elm.index());
});


来源:https://stackoverflow.com/questions/16134640/jquery-on-click-second-time-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!