简体   繁体   English

jQuery更改类和触发器

[英]Jquery changing class and trigger

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <span class="fake_h">Too</span> </body> <script> $('.fake_h').click(function() { $(this).addClass('active_h').removeClass('fake_h'); }) $('.active_h').click(function() { alert() }) </script> 

When I click on span it removes the class fake_h and add active_h . 当我单击span时,它将删除类fake_h并添加active_h But after that when I click span(class='active_h') It doesn't work. 但是之后,当我单击span(class='active_h')它将不起作用。 Don't trigger alert or anything. 不要触发警报或其他任何东西。 Can anyone explain why it doesn't work. 谁能解释为什么它不起作用。

You can do it like this. 您可以这样做。

$(document).ready(function(){
    $('.fake_h').click(function(){
       $(this).addClass('active_h');
       $(this).removeClass('fake_h');
    });

    $('body').on("click", '.active_h', function(){ 
       alert('active_h'); 
    });
});

Wrap your span with some div and use that div class to trigger your dynamic added class . 用一些div包装您的span ,并使用该div class触发动态添加的class Changing the identifiers dynamically need to use delegated event handlers. 动态更改标识符需要使用委托事件处理程序。

 $('.yourClass').on("click", '.fake_h', function() { $(this).addClass('active_h').removeClass('fake_h'); }) $('.yourClass').on("click", '.active_h', function() { alert() }) 
 .active_h { text-decoration: underline } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div class='yourClass'> <span class="fake_h">Too</span> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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