Add/remove class working but clicking on new class doesn't
Sorry for the bad title wording!
I have the JS:
$(".add").click(function(event)
{
cid=event.target.id;
alert("add class changed");
$("#"+cid).addClass("del");
$("#"+cid).removeClass("add");
});
$(".del").click(function(event)
{
cid=event.target.id;
alert("del class changed");
$("#"+cid).addClass("del");
$("#"+cid).removeClass("add");
});
And some html like this:
<a class="add" id="1" href="#">test a</a>
<a class="add" id="2" href="#">test b</a>
<a class="add" id="3" href="#">test c</a>
When I click on one of the "tests" I get the "add class changed" alert and the HTML shows it's class has been changed to "del".
However when I click on one of the changed "tests" the function for something with a del class doesn't run, just the add one again.
So the class is changing and displaying accordingly, but the click function for the corresponding class isn't happening. Can anyone see where I'm going wrong?
EDIT: Needed a "LIVE" event. The following code works:
$(".add").live({
click: function(event)
{
cid=event.target.id;
alert("add class changed");
$("#"+cid).addC开发者_运维百科lass("del");
$("#"+cid).removeClass("add");
}
});
The $(".add")
just selects elements that at that moment have the add
class. It doesn't mean the click event will magically be assigned to other elements when their classes change.
This can be achieved, though, by using the JQuery live method to bind the events.
精彩评论