为什么输入内的标签触发点击事件 [英] Why Does a Label Inside an Input Trigger a Click Event

查看:111
本文介绍了为什么输入内的标签触发点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在标签中有一个输入,为什么句子中的每个单词都会触发点击事件?

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.

我在输入标签中使用 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:


  1. 有没有办法在标签中使用输入,方式是 label 不会触发点击事件?

  2. 在我的例子中,为什么click事件触发了每个单词?
  3. >
  1. Is there a way to use an input inside a label in a way that the label does not trigger the click event?
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆