简体   繁体   English

如何使jQuery click()函数仅运行一次

[英]How to make jQuery click() function only run once

I have a scenario where I want an event to happen when a button is clicked, but then I want a different behavior when it's clicked the second time. 我有一种情况,我希望单击按钮时会发生事件,但是当第二次单击按钮时又希望有不同的行为。 Here's an example of what's happening: 这是正在发生的事的一个例子:

 $('.click').not('.clicked').click(function () { $(this).addClass('clicked'); $('<p class="test">Test</p>').insertAfter(this); }); 
 .clicked { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='button' class="click" value="Click Me" /> <input type='button' class="click clicked" value="Click Me" /> <input type='button' class="click" value="Click Me" /> 

What I want it to do is stop running the jQuery once the class .clicked is added to the button. 我想做的是一旦将.clicked类添加到按钮中,就停止运行jQuery。 This works the way I would expect, if the button already has the class applied, but if I add the class with jQuery it doesn't stop running my function each time the button is clicked. 如果按钮已经应用了该类,则可以按我期望的方式运行,但是如果我使用jQuery添加该类,则每次单击按钮时,它不会停止运行我的函数。

It does not matter which type of CSS selector you use because it will be executed only once. 使用哪种类型的CSS选择器都没有关系,因为它只会执行一次。 So you are adding an event listener for every tag with the class .click and without .clicked . 所以,你要添加的事件侦听器与类中的每个标签.click并没有.clicked You should do something like this: 您应该执行以下操作:

 $(document).on('click', '.click:not(.clicked)', function () { $(this).addClass('clicked'); $('<p class="test">Test</p>').insertAfter(this); }); 
 .clicked { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='button' class="click" value="Click Me" /> <input type='button' class="click clicked" value="Click Me" /> <input type='button' class="click" value="Click Me" /> 

Adding the event listener to the whole document and later selecting the tags using .click:not(.clicked) allows you to "evaluate" the css selector every single time. 将事件侦听器添加到整个文档,然后再使用.click:not(.clicked)选择标签,可以使您每次“评估” css选择器。

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

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