繁体   English   中英

jQuery:传播事件和动作

[英]jQuery: propagating events & actions

抱歉错误的标题。

JSFiddle链接

描述:

我有2个事件附加到同一元素,具有不同的类,具体取决于它的状态。

第一次click事件会添加expanded类并更改其文本(仅用于可见性)。

第二次click事件附加到由expanded类修改的元素。

问题:

第二次click事件永远不会触发。 不删除类并更改文本。


如果你在没有event.stopPropagation情况下尝试它,它会立即触发第一次和第二次click事件,第一次不会对元素进行任何视觉上的更改。

jQuery的

$('button').click(function() {
    $(this).addClass('expanded');
    $(this).text('Expanded class added');
    event.stopPropagation();
});
$(document).on('click','button.expanded', function() {
    $(this).removeClass('expanded');
    $(this).text('Expanded class removed')
});

问题是:如何正确执行点击事件,他们两人都做了他们应该做的事情?

  1. button上绑定事件
  2. 检查单击的按钮是否已expanded类,如果存在则删除它,否则添加它。
  3. 更新单击元素的innerText。 三元运算符使用$(this).hasClass('expanded') ? "added" : "removed") $(this).hasClass('expanded') ? "added" : "removed")将返回"added"如果按钮类expanded加入( 在第二步骤 ),否则返回"removed"

码:

$(document).on('click', 'button', function () {
    $(this).toggleClass('expanded') // Toggle `expanded` class of the clicked button
        .text('Expanded class ' + ($(this).hasClass('expanded') ? "added" : "removed")); // Update text
});

-DEMO-

编辑:为了好玩,设置文本按钮内容,你可以使用CSS伪元素:

 $(document).on('click','button', function() { $(this).toggleClass('expanded'); }); 
 button:not([class]):before { content: "Click me" } button.expanded:after { content: "added"; } button[class]:not(.expanded):after { content: "removed"; } button[class]:before { content: "Expanded class " } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button></button> 

我认为更简单的思考方法是将两个处理程序放在委派的click事件中:

$(document).on('click','button', function(event) {
    if ($(event.target).hasClass('expanded')) {
        $(event.target).removeClass('expanded');
        $(event.target).text('Expanded class removed')
  }
  else {
        $(event.target).addClass('expanded');
        $(event.target).text('Expanded class added');
  }
  return false;
});

更新的小提琴: https//jsfiddle.net/jvL8z2dw/4/

使这个小清洁和坚固。

 $('button').click(function() { $(this).toggleClass("expanded"); if ($(this).hasClass("expanded")) { $(this).text('Expanded class added'); } else { $(this).text('Expanded class removed') } return false; }); 
 .expanded { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Click me</button> 

这应该为你做

$(document).on('click', 'button', function (event) {
    $(this).toggleClass('expanded')
    if($(this).hasClass('expanded')) {
        $(this).text('Expanded class added');
    } else {
        $($this).text('Expanded class removed')
    }
    return false;
});

暂无
暂无

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

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