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 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
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 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
Share Improve this question edited Feb 22, 2011 at 15:52 Rrryyyaaannn asked Feb 22, 2011 at 15:47 RrryyyaaannnRrryyyaaannn 2,5975 gold badges19 silver badges15 bronze badges 3- Your JS is syntactically invalid - you're missing a closing single quote. Is that what your actual code looks like, or did you just type it into the question incorrectly? – Matt Ball Commented Feb 22, 2011 at 15:49
- 1 No, that's not possible. Please show us an example. – SLaks Commented Feb 22, 2011 at 15:50
- Oops, you're right about the single quote. This is not my actual code, but this is identical to what I was trying to do. Is there another way to do it? – Rrryyyaaannn Commented Feb 22, 2011 at 15:52
3 Answers
Reset to default 4To fix the syntax error:
$('.image').load(function(){
$(this).parents('.image-wrapper').removeClass('image-wrapper').addClass('image-wrapper-new');
});
I would also remend 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
});
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745222254a4617301.html
评论列表(0条)