简体   繁体   English

为什么用跨度来处理“单击,按钮”呢?

[英]Why is an on “click, ”button" being handled by a span instead?

I'm experiencing something that seems quite wrong with events and jquery . 我遇到了一些事件和jquery似乎很不对劲的事情。

I have the following simple HTML list 我有以下简单的HTML列表

<ul>
  <li><button class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus-sign"></span></button> Chocolate</li>
  <li><button class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus-sign"></span></button> Butter</li>
  <li><button class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus-sign"></span></button> Milk</li>
  <li><button class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus-sign"></span></button> ugar</li>
</ul>

and the following JavaScript: 以及以下JavaScript:

$(document).on("click", "button", function(evt) {
  console.debug("got a click in", evt.target);
});

When I click in a button I get 当我单击按钮时,我得到

got a click in <span class="glyphicon glyphicon-minus-sign"></span>

and not in the button. 而不是在按钮上

Why? 为什么?

The target property of event objects points to the originator of the event; 事件对象的target属性指向事件的发起者; here, it's the element that was the first target of the click, and that was apparently the <span> . 在这里,元素是点击的第一个目标,显然是<span>

If you want the element selected by .on() , jQuery provides it as this . 如果您希望通过.on()选择元素,则jQuery this提供它。

$(document).on("click", "button", function(evt) {
    console.debug("got a click in", this);
});

(Note that you don't have to wait for $(document).ready when using delegation rooted in document .) (请注意,使用以document根的委派时,不必等待$(document).ready 。)

Any element can receive a click event. 任何元素都可以接收点击事件。 If it doesn't handle it the event will "bubble up" through parent elements. 如果不处理,事件将通过父元素“冒泡”。

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

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