开发者

Add Class in jQuery & Run Function on New Class

开发者 https://www.devze.com 2023-03-23 20:57 出处:网络
I\'m attempting to addClass to an href, and then later run a function on t开发者_JS百科hat new class.

I'm attempting to addClass to an href, and then later run a function on t开发者_JS百科hat new class.

The problem is once the class is added, I can not get any js to work on it.

Here's a fiddle:

http://jsfiddle.net/3hp9f/2/


You have a couple errors:

This works:

$("a.theLink").click(function(event){
    event.preventDefault();
    $(this).addClass("live");
});

$("a.live").live('click',function(event){
    event.preventDefault();
    alert("YO!");
});

You need to prevent the default event behavior, and also add a future-proof event observer such as live() or delegate() since you are adding the class to the object after the bind has been set.

http://jsfiddle.net/AlienWebguy/3hp9f/16/


You are attaching the a.live event handler before the object has the class, move the handler inside the first one, ie

$("a.theLink").click(function(){
    $(this).addClass("live");
    $("a.live").click(function(){
         alert("YO!");
         return false;
     });
    return false;
});

This is not the best way but I hope it shows you what is wrong.


You can use the live (API Ref) method for this, which attaches an event to all current and future matches to the selector:

$("a.live").live('click', function(){
    alert("YO!");
    return false;
});


Here you go: http://jsfiddle.net/Skooljester/KcG8g/. You needed to use .live instead of .click.


Try this

$("a.theLink").click(function(){
    $(this).unbind('click').addClass("live");
    return false;
});

$("a.live").live('click', function(){
    alert("YO!");
    return false;
});

The code isn't exactly how you had it but there are some issues. I used $('').live but you might want to bind the event inside of your first click event. Also know that if you return false from your events instead of using preventDefault only the first click event will fire.

0

精彩评论

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