相关元素上的 JavaScript 事件

发布于 2025-01-04 12:43:26 字数 337 浏览 0 评论 0原文

我想知道以下行为是否正确。

我有一个通过“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酷到爆炸 2025-01-11 12:43:26

单击label将触发附加到该label的任何onclick函数任何onclick附加到输入本身。单击input触发inputonclick

这很容易测试。请参阅此处:

Clicking the label will trigger any onclick function attached to that label and any onclick attached to the input itself. Clicking the input will trigger only the onclick for the input.

This is very easy to test. See here:

玩世 2025-01-11 12:43:26

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文