问题
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