相关元素上的 JavaScript 事件
我想知道以下行为是否正确。
我有一个通过“for”属性链接到输入元素的标签元素,这是否会在单个用户单击标签时产生两个单击事件?具体来说,在窗口上放置一个点击侦听器。然后,定义复选框,并使用属性“for”链接到它的标签元素。单击标签文本。结果是复选框将被选中,您将看到两个单击事件。 http://jsfiddle.net/k55uD/2/
如果这种行为是正确的,是否还有更多这样的行为案例、属性或其他什么?一些规格会很好。
任何帮助表示赞赏。
PS 我用这个例子更新了这篇文章。
I am wondering is the following behavior correct.
I have a label element linked to an input element via the "for" attribute, should this yield two click events on a single user click on the label? Specifically, put a click listener on window. Then, define checkbox with a label element linked to it using attribute "for". Click on the label text. The result is that checkbox will be checked and you will see two click events. http://jsfiddle.net/k55uD/2/
If this behavior is correct, are there more such cases, attributes, or whatever? Some spec would be nice.
Any help is appreciated.
P.S. I update the post with the example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
单击
label
将触发附加到该label
的任何onclick
函数和任何onclick
附加到输入
本身。单击input
将仅触发input
的onclick
。这很容易测试。请参阅此处:
Clicking the
label
will trigger anyonclick
function attached to thatlabel
and anyonclick
attached to theinput
itself. Clicking theinput
will trigger only theonclick
for theinput
.This is very easy to test. See here:
DOM 会单独处理每个元素,因此标签和它所“针对”的元素都可以定义事件处理程序。所以是的,如果两个元素都有一个 onclick 处理程序并且单击位于每个元素内,则两个事件都会触发。
然而,这是您必须定义的内容,默认情况下您不会因为标签“用于”另一个元素而在标签上获得第二次单击。
基本上,这取决于您 - 您可以将其设置为引发两个事件或单个事件,但开箱即用,您将为定义处理程序的元素引发一个事件。
这很好地解释了事件和事件顺序,并提供了一些有关浏览器怪癖的建议。
http://www.quirksmode.org/js/events_order.html
编辑:
如果您具体来说,在窗口上放置一个点击侦听器。然后,您将因传播而获得这两个事件,这在提供的链接中再次进行了解释。
The DOM would treat each element separately, so both the label and the element it is 'for' can have event handlers defined. So yes, if both elements have an onclick handler and the click is within each element, both events will fire.
However this is something you have to define, you don't get a second click by default on the label just because it is 'for' the other element.
Basically, it is up to you - you can set it up to raise two events or a single event but out of the box you will get one event raised for the element you defined the handler on.
This explains events and event order pretty well, as well as offering some advise about browser quirks.
http://www.quirksmode.org/js/events_order.html
EDIT:
If you Specifically, put a click listener on window. Then you will get both events due to propagation, again this is explained in the link provided.