简体   繁体   English

使用jQuery通过添加/删除类来控制点击事件

[英]Using jQuery to control click events by adding/removing classes

I currently have something like this code running: 我目前正在运行类似以下代码的内容:

function blah() {
jQuery(".class1").on("click", function() {
    jQuery(this).text('Validate').addClass('class2').removeClass("class1");
   //more stuff here
    jQuery(".class2").on("click", function() {
           jQuery(this).removeClass("class1");
           //More stuff here

This is bad because the click events propagate, every click that occurs adds the click event multiple times. 这很不好,因为单击事件会传播,每次发生的单击都会多次添加单击事件。 I tried closing off the first selector (like so) and having the click events seperately but the second click event never occurred(!): 我试图关闭第一个选择器(像这样),并分别单击事件,但第二个单击事件从未发生(!):

function blah() {
jQuery(".class1").on("click", function() {
    jQuery(this).text('Validate').addClass('class2').removeClass("class1");
});
jQuery(".class2").on("click", function() {
           jQuery(this).removeClass("class1");
           //More stuff here

How do I structure code so that on the first click one thing happens, and the second click another thing happens without click events doubling 如何构造代码,以便在第一次单击时发生一件事情,而在第二次单击时发生另一件事而没有将点击事件加倍

you need 你需要

jQuery(document).on("click", ".class1", function() {
    jQuery(this).text('Validate').addClass('class2').removeClass("class1");
});
jQuery(document).on("click", ".class2", function() {
           jQuery(this).removeClass("class1");
           //More stuff here
});

Demo: Fiddle 演示: 小提琴

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

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