简体   繁体   中英

JQuery not selector on dynamically added class

I want to add a click event on a like button. When clicked I want to add a class called active. When the element has this class I do not want the click event to fire.

Why does this log "clicked!" every time and not only the first?

http://jsfiddle.net/M5MRQ/

<div class="vote">
    <a class="vUp">Like me</a>
</div>

$(".rate .vUp").not(".active").click(function(){
    console.log("click!");
    $(this).addClass("active");
    return false;
});

You can simply unbind event on click using .off()

$(".rate .vUp").click(function(){
    console.log("click!");
    $(this).addClass("active");

    //Unbind event
    $(this).off("click");
    return false;
});

DEMO

That's because, your DOM changes at runtime, but your JS doesn't. You need a live method, or better, remove the click handler on the button like this:

$(".rate .vUp").click(function(event){
    console.log("click!");
    $(this).addClass("active");
    $(event.currentTarget).unbind("click");
    event.preventDefault();
    return false;
});

see here http://jsfiddle.net/M5MRQ/7/

Try to use following code:

$(".rate .vUp").click(function(){
    if($(this).hasClass("active")){
        return false;
    }else{
        console.log("click!");
        $(this).addClass("active");
    }             
});

You can use the hasClass() method as well to get a working example:

$(".rate .vUp").click(function(){
    if (!$(this).hasClass("active")) {        
        console.log("click!");
        $(this).addClass("active");
        event.preventDefault();
        return false;
    }
});

see http://jsfiddle.net/M5MRQ/9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM