开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜