为什么单击处理程序被调用两次
why is click handler called twice
我创建了一个非常简单的jsFiddle示例,其中单击处理程序被分配给两个单选按钮:
$(document).ready(function () {
$(".title").on("click", function (event) {
alert('clicked');
});
});
如您所见,每次选择单选按钮时,都会调用处理程序两次,为什么?
<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>
您在
两个标签中使用title
类,这意味着它在两个单选盒上使用。单击它时,它会在两个单选框上触发事件。您应该使用单选按钮选择器完成工作:
$(document).ready(function () {
$(":radio").on("change", function (event) {
alert('clicked');
});
});
演示
引用更改
通过点击
$(document).ready(function () {
$(":radio").on("click", function (event) {
alert('clicked');
});
});
演示
发生这种情况是因为您的<input>
标签位于<label>
标签内;由于单击标签也会触发对收音机的点击,因此您基本上单击收音机两次。
如果将<input>
标记移出<label>
标记,则应该没问题。
尝试
$(".title input").on("click", function (event) {
alert('clicked');
});
使用更改事件。它会正常工作。
$(document).ready(function () {
$(".title").on("change", function (event) {
alert('clicked');
});
});
这与
我的事情title
元素的范围有关。
添加到输入,然后将事件绑定到该类,它将正常工作。
.HTML:
<label class="title">
<input type="radio" class='checkbox' name="heading" checked="checked" />Introduction and General Information about the Marketing Tool</label>
<label class="title">
<input type="radio" class='checkbox' name="heading" />Implementation Steps of the Marketing Tool</label>
脚本:
$(document).ready(function (e) {
$(".checkbox").on("click", function (event) {
alert('clicked');
});
});
小提琴
问题来自<label>
因为当您单击标签时,无线电也会被单击,反之亦然。如果将<label>
更改为<p>
,将解决此问题: 在这里演示
<p class="title">
<input type="radio" name="heading" checked="checked" />Introduction and General Information about the Marketing Tool
</p>
<p class="title">
<input type="radio" name="heading" />Implementation Steps of the Marketing Tool
</p>
或者只是尝试仅将单击事件添加到输入中,如下所示:
$(document).ready(function () {
$(".title input[type='radio']").on("click", function (e) {
alert('clicked');
});
});
做了一些修改,它工作正常......虽然你的代码是正确的,但这是你的例子
$(document).ready(function () {
$("input[type=radio]").on("click", function (event) {
alert('clicked');
});
});
相关文章:
- Meteor Router数据函数被调用两次
- Backbone.js ListenToOnce被调用两次
- 当我的单元测试失败时,回调被调用了两次
- 我的jQuery加载请求是否被调用了两次
- 为什么DTM数据元素被调用两次
- jQuery 方法调用了两次
- 模态中的数据关闭在单击时被调用两次
- 调用一个函数两次
- java-script 函数被调用两次
- 查找与通过两次调用地理编码创建的两个 latlng 对象的距离
- Primefaces:RequestContext.execute-调用了两次Javascript
- 在一个页面中包含两次的脚本中调用函数
- 调用随机函数Javascript,但不能两次调用相同的函数
- 如何防止在快速单击时两次调用en事件处理程序
- 在AngularJS中,一次进行两次调用是一种可接受的方法
- jquery停止两次调用委派事件
- 我没有'我不想两次调用自定义函数
- Javascript:两次调用函数会导致不必要的行为
- 当两次调用一个方法时,仅呈现一个SVG组件
- JavaScript在两次调用之间占用额外时间