简体   繁体   中英

click() after changed class

I have this code:

$(document).ready(function(){
    $('.notUsed').click(function(){
        $(this).attr('class', 'used');
    });
});

$(document).ready(function(){
    $('.used').click(function(){
        alert("Are you sure you want to do this?");
    });
});


<div class="notUsed"></div>

And after I click on the div the first time everything works fine, the stlye changes and everything. But when i click on it the second time, the second event won't trigger. What am I doing wrong?

This syntax:
$('.used').click(function(){
binds all the current elements with the classname 'used'. Since the used class is added after the document is initially loaded, you need to bind it dynamically:
$(document).click('.used',function(){
If possible, you should use the parent of .used as a selector instead of the document.

Event handlers are bound at runtime - so when your class changes the second handler still does not know about that element. You can either bind the second handler at the time of class change or use event delegation. Also, you only need 1 DOM ready event:

$(document).ready(function(){
    $('.notUsed').click(function(){
        $(this).addClass('used').removeClass('notUsed');
        $(this).off("click"); //unbind this handler

        $('.used').click(function(){
            alert("Are you sure you want to do this?");
        });
    });
});

It never binds beceuse when you run $('.used').click(function(){ there is no element .used this should work

$(document).ready(function(){
    $('.notUsed').live('click', function(){
        $(this).attr('class', 'used');
    });

    $('.used').live('click', function(){
        alert("Are you sure you want to do this?");
    });
});


<div class="notUsed"></div>

You need to use delegation for your events to work:

$(document).ready(function () {
    $('.not-used').on("click", function () {
        $(this).removeClass('not-used').addClass('used');
    });

    $(document).on('click', '.used', function () {
        alert("Are you sure you want to do this?");
    });
});

You have the element right there in the callback why not bind a new EventListener to it

$(document).ready(function () {
  $('.not-used').on("click.first", function () {
    $(this)
      .removeClass('not-used')
      .addClass('used')
      .off('click.first')
      .on('click.second', function(){
        alert("Are you sure you want to do this?");
    });
  });
});

I think you can use

<div class="element used"></div>

To handle click

$(".element").on("click",function(){
     this.classList.toggle("used");
     this.classList.toggle("notUsed");
});

Just handle event 1 time.

Hope it'll help you

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