Reputation: 2337
I'm having trouble building a bit of jquery that grabs a selector that has been modified after a previous event.
For example, I have a some html which looks like this:
<div class='1'>test</div>
if i click it with the following:
$(".1").click(function(){
alert('found 1!');
$(this).attr('class', '2');
});
the alert works and when i inspect the element, the class has been switched to '2'
now when i click it again, with the following:
$(".2").click(function(){
alert('found 2!');
$(this).attr('class', '1');
});
I still get 'found 1!' as an alert.
Is what i'm trying not possible for some reason, am i doing it wrong or is there a better way of doing it? Thanks!
Upvotes: 3
Views: 311
Reputation: 707376
When you do this:
$(".1").click(function()
You are binding to a specific DOM element. Once it's bound, it no longer matters what class is on the object. The event handler is bound to the object itself. The way jQuery executes this statement is that it finds all the DOM objects with class="1"
and sets an event listener on them.
If you want event handlers to handle dynamic changes to the page, then you need to use jQuery's .live()
or .delegate()
(jQuery 1.6 or before) or jQuery's .on()
(jQuery 1.7+).
Upvotes: 1
Reputation: 5091
You need to use jquery .on() (or .delegate()) function to bind events for dynamically updated elements.
As below code,
$(".1").on("click", function(){
alert('found 1!');
$(this).attr('class', '2');
});
$(".2").on("click",function(){
alert('found 2!');
$(this).attr('class', '1');
});
Upvotes: 4
Reputation: 17434
.click() binds only at execution time. What you are looking for is .live() or .on(). I'll use .on(), the jQuery 1.7 syntax:
$(document).on("click", ".1", function() {
console.log('1 clicked');
$(this).attr('class', '2');
});
$(document).on("click", ".2", function() {
console.log('2 clicked');
$(this).attr('class', '1');
});
Upvotes: 3