问题描述:

So I have a rails app that renders views via jquery-ujs. (data-remote in the URLs, then a load of js.erb files with things like:

$('#whatever').html('<%= j render("form") %>');

In my main JS file, I have event handlers like so:

$('.action').on('click', function() {

console.log("clicked");

});

but the on() behaviour does not attach to the new elements inserted by jquery-ujs. I can go into the console and paste the above code and everything attaches fine (once the elements are already there), but straight after ujs fires, no luck. Is this a bug or am I doing something wrong?

This is with jQuery 1.9.1 and Rails 3.2.13 btw.

网友答案:

You need to bind on to a parent like document. Now, you're binding directly to the .action element, which is essentially the same as using $('.action').click(). Because you're adding elements to the DOM later, you need to delegate the handler to something that's already present before the elements are inserted. You can provide a selector as the second parameter of the .on event to bind it to .action.

Have a look at the 'Direct and delegated events' section in jQuery's API documentation for .on.

This should work:

$(document).on('click', '.action', function () {
    console.log('Clicked!');
});
网友答案:

Since #whatever seems to be static (exists all the time) you can delegate the handling to it..

$('#whatever').on('click','.action', function(e){
    console.log("clicked");
});

(assuming that the .action elements are added inside the #whatever element)


See http://api.jquery.com/on/#direct-and-delegated-events for more on delegated events

相关阅读:
Top