简体   繁体   English

jQuery选择器未注册添加的类

[英]jQuery selector doesn't register the added class

Can anyone please explain me why this code does what it does. 任何人都可以请我解释一下为什么此代码可以做到这一点。

What I would like to achieve is that when the first button gets clicked javascript adds a disabled class to the second button and when the second button gets pressed with disabled class the javascript won't run. 我想实现的是,当单击第一个按钮时,javascript将禁用的类添加到第二个按钮中,而当第二个按钮被禁用类按下时,则javascript将不会运行。

<!DOCTYPE html>  
<html lang="en">  
<head>
<meta charset="utf-8" />  
<title>jQuery question</title>  
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<style>
a.success { background: green }
</style>
</head>  
<body>
    <div id="holder">
        <a href="#" class="button">Button 1</a>
        <a href="#" class="button">Button 2</a>
    </div>
</body>
<script>
$(function(){

  $('#holder a.button:not(.disabled)').on('click', function() {

    // Toggle success class
    if($(this).hasClass('success')) {
        $(this).removeClass('success');
    }
    else {
        $(this).addClass('success');
    }

    // Add disabled class to the not so lucky button 
    $('#holder a.button:not(.success)').each(function() {
        $(this).addClass('disabled');
    });

  });

});
</script>
</html>

Looking at the console this is not the case. 从控制台看情况并非如此。 Even though the second button gets the disabled class. 即使第二个按钮获得了禁用的类。 Pressing the disabled button still runs javascript despite the :not(.disabled) selector. 尽管:not(.disabled)选择器,按禁用按钮仍然运行javascript。

It behaves as expected when I change it like this 当我像这样更改它时,它的行为符合预期

$('#holder a.button').on('click', function() {
    if($(this).hasClass('disabled')) {
      return false;
    }

But could someone please explain why it's acting like that? 但是有人可以解释为什么会这样吗?

The selector is not going to dynamically re-evaluate itself every time an event is fired. 选择器不会在每次触发事件时动态地重新评估自己。

The best way to solve this problem would be to use event delegation: 解决此问题的最佳方法是使用事件委托:

$('#holder').on('click', '.button:not(.disabled)', function() {
    // snip...
});

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

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