使用输入时发现了以下行为。当标签附加到具有for
属性的输入时,将发生两个单击事件。有人可以解释一下这个“异常”的行为吗?
如果有一种方法可以防止在仅单击标签的情况下在输入上发生单击,当然除了删除属性之外for
。
document.addEventListener(`click`, onClick)
var counter = 0;
function onClick(event) {
++counter
console.log(counter)
}
Run Code Online (Sandbox Code Playgroud)
label {
display: block;
background-color: lightgrey;
margin: 5px 0 5px;
}
Run Code Online (Sandbox Code Playgroud)
<input id='input'>
<label for='input'>I belong to input</label>
<label>I belong to no one</label>
Run Code Online (Sandbox Code Playgroud)
我已经创建了一个非常简单的jsFiddle示例,它将一个点击处理程序分配给两个单选按钮:
$(document).ready(function () {
$(".title").on("click", function (event) {
alert('clicked');
});
});
Run Code Online (Sandbox Code Playgroud)
如您所见,每次选择一个单选按钮时,处理程序被调用两次,为什么?
<label class="title">
<input type="radio" name="heading" checked="checked" />Introduction and General Information about the Marketing Tool
</label>
<label class="title">
<input type="radio" name="heading" />Implementation Steps of the Marketing Tool
</label>
Run Code Online (Sandbox Code Playgroud) 我有一组这样的项目:
<label for="Cadenza-1" class="cars">
<input type="checkbox" value="1" alt="Cadenza" id="Cadenza-1" name="vehicles[]">
<img src="img/bill_murray_173x173.jpg">
<span>Cadenza</span>
</label>
Run Code Online (Sandbox Code Playgroud)
大约有 13 个。我想在单击时向标签添加一个类。但是,单击事件会触发两次。现在我正在调试单击事件,然后我将添加该类:
var cars = document.getElementsByClassName('cars');
for(var c = 0;c < cars.length; c++){
cars[c].addEventListener("click", function(e){
selectVehicle(cars[c],e);
},false);
}
function selectVehicle(el,e) {
console.log(e);
e.stopPropagation();
}
Run Code Online (Sandbox Code Playgroud)
该console.log
闪光两次。