jquery 中的条件开启关闭事件绑定

conditional on off event binding in jquery

我正在尝试使用 jQuery 绑定按钮的关闭事件。

第一次(文档完全加载时)我必须点击按钮两次才能看到效果。

p 标签的点击也不起作用。

    <p>Click the button below</p>
    <button class="blue">Remove the click event handler</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        function changeColor(evt) {
            $('p').css("background-color", $(evt.target).attr('class'));
            $(evt.target).removeAttr('class').attr('class', 'pink');
        }
        $("button").click(function () {
            if ($(this).hasClass('pink')) {
                $(this).off("click", changeColor);
            }
            else {
                $(this).on("click", changeColor);
            }
        });
        $("p").on("click", function () {
            $('button').removeAttr('class').attr('class', 'green').on("click", changeColor);
        });
    </script>

我建议您在操作选择器时使用 Event Delegation 方法,即删除和添加 类.

$(document).on('click', "button:not(.pink)", changeColor)

您应该使用最近的静态容器代替 document

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

$(document).on('click', "button:not(.pink)", function() {
  $(this).removeClass().addClass('pink');
  console.log('Clicked')
})
.blue {
  background-color: blue;
}

.pink {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button class="blue">Remove the click event handler</button>
<button class="blue">Remove the click event handler</button>


要以编程方式触发事件,您需要使用 .trigger()

$('button').removeClass().addClass('green').trigger('click');