JS/Jquery: Click Event After AddClass
Say I want to change a container's class when the image it contains is loaded, probably something like this:
$('.image').load(function(){
$(this).parents('.image-wrapper').removeClass('image-wrapper').addClass('image-wrapper-new');
});
…And then add a click event, referencing the newly-added class, like this:
$('.image-wrapper-new').click(function(){
//Do stuff
});
I've tried something similar to this, with no success. Am I missing something?
Using Developer开发者_JS百科 Tools, it appears that the browser is rendering it as .image-wrapper-new, but since it retains the .image-wrapper class in the physical code, Jquery/JS doesn't honor it. Is that possible?
Thanks.
-Ryan
To fix the syntax error:
$('.image').load(function(){
$(this).parents('.image-wrapper').removeClass('image-wrapper').addClass('image-wrapper-new');
});
I would also recommend using .on()
rather than .click()
so you don't have to re-bind event handlers every time you change the class:
$(document).on('click', '.image-wrapper-new', function(){
//Do stuff
});
You should be using .live('click', function() {}); due to the fact that you are updating the DOM. .click() will not pick up on new data automatically. If you are building an ajax application this should be standard imo
Just add your click event handler in the same function, as you change class:
$('.image').load(function(){
$(this).parents('.image-wrapper')
.removeClass('image-wrapper')
.addClass('image-wrapper-new')
.click(function(){
//Do stuff
});
});
精彩评论