gpt4 book ai didi

javascript - 一个莫名其妙的点击事件 : Why such behaviour?

转载 作者:行者123 更新时间:2023-11-30 12:31:24 28 4
gpt4 key购买 nike

我最近正在测试 <label> 的点击事件(点击后找到一个文本框)并发现了一些不寻常的东西。

在 HTML 标记中,

  • 如果<input><label>里面, 上面的点击事件标签触发了两次
  • 如果<input><label>之外,点击事件为按预期运行

为了更好地理解我要提出的建议,请参阅 JS Fiddle 处的 fiddle

我因此感到莫名其妙,无法弄清楚背后的原因。有没有人要?

最佳答案

If the <input> is inside the <label>, the click event on that label is firing two times

因为事件在 DOM 中“冒泡”,从接收初始事件的元素(event.target,这里是 <input />)通过祖先。因为监听器附加到 <input /> 的父级它首先在其后代上检测到点击时触发,然后在点击冒泡时再次触发。

为防止这种情况,您可以使用 event.stopPropagation()以防止冒泡。

因为 event ,在这种情况下,已经冒泡到 <label> alert() 处的元素/event-handler 被解雇,你必须显式调用 event.stopPropagation()<input /> 上本身,而不是附加到 <label> 的事件处理程序中:

$(function() {
$('label input').click(function(event) {
event.stopPropagation();
});

$(".v1 li label").click(function() {
var ct = $(this).find("input").val();
alert(ct);
});

$(".v2 li label").click(function() {
var ct = $(this).parent().find("input").val();
alert(ct);
});
});
ul {
padding: 10px;
}
li {
list-style: none;
margin-bottom: 5px;
}
li label {
display: block;
background-color: #f0f0f0;
padding: 5px;
cursor: pointer;
border: 1px solid #ccc;
}
li input {
display: none;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3><i>input</i> inside <i>label</i></h3>

<ul class="v1">
<li>
<label for="l1">
<input type="radio" name="a" value="1" id="l1" />First</label>
</li>
<li>
<label for="l2">
<input type="radio" name="a" value="2" id="l2" />Second</label>
</li>
<li>
<label for="l3">
<input type="radio" name="a" value="3" id="l3" />Third</label>
</li>
</ul>
<hr />
<h3><i>input</i> outside <i>label<i></h3>
<ul class="v2">
<li>
<label for="ll1">Fourth</label>
<input type="radio" name="b" value="4" id="ll1" />
</li>
<li>
<label for="ll2">Fifth</label>
<input type="radio" name="b" value="5" id="ll2" />
</li>
<li>
<label for="ll3">Sixth</label>
<input type="radio" name="b" value="6" id="ll3" />
</li>
</ul>

引用资料:

关于javascript - 一个莫名其妙的点击事件 : Why such behaviour?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27600113/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com