为什么单击处理程序被调用两次

why is click handler called twice

本文关键字:两次 调用 单击 处理 程序 为什么      更新时间:2023-09-26

我创建了一个非常简单的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');
        });
    });