为什么输入内的标签触发点击事件 [英] Why Does a Label Inside an Input Trigger a Click Event
问题描述
如果我在标签
中有一个输入
,为什么句子中的每个单词都会触发点击事件?
If I have an input
inside a label
, why does every word in the sentence trigger a click event?
以下是一个示例 jsFiddle 。无论您在第一句中点击什么字词,该事件都会被解雇。
Here is a jsFiddle for an example. No matter what word you click on in the first sentence, the event is fired.
我在输入$ c $中添加了一些CSS所以你可以看到,无论你将鼠标悬停在第一个标签的哪个位置,这就像你在输入上盘旋。我还在
标签
中使用 a
标签添加了第二个标签,它的工作方式与我期望的 input
工作(点击标签中的单词时点击事件不会触发)。
I added some CSS on the input
so you can see that no matter where in the first label you mouse over, it's like you are hovering over the input. I also added a second label using an a
tag inside the label
which works as I would expect the input
to work (the click event does not fire when you click on a word in the label).
<label>Click <input type="submit" value="here" /> to go somewhere.</label>
<label>Click <a href="#">here</a> to go somewhere else.</label>
$('input, a').click(function() {
alert('Clicked');
});
我的两个问题是:
My two questions are:
- 有没有办法在
标签
中使用输入
,方式是label
不会触发点击事件? - 在我的例子中,为什么click事件触发了每个单词? >
- Is there a way to use an
input
inside alabel
in a way that thelabel
does not trigger the click event? - In my example, why does the click event fire on every word in the sentence?
推荐答案
这是HTML规范的一部分 - label
元素会增加相关输入
的命中区域。您可以自己处理点击操作, preventDefault()
,但它不会停止点击时按钮UI的更改。
This is part of the HTML spec - label
elements increase the hit area of the related input
. You can handle the click yourself and preventDefault()
, however it will not stop the button UI changing on click.
或者,您可以更改将标签
元素设置为 span
,并使用适当的样式使它们的行为方式相同,尽管您会伤害用户'的经验。
Alternatively you could change the label
elements to span
with the appropriate styling to make them behave the same way, although you will be hurting your users' experience.
这篇关于为什么输入内的标签触发点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!