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

时间:2013-09-13 13:38:47

标签: javascript jquery

我创建了一个非常简单的jsFiddle example点击处理程序,分配给两个单选按钮:

    $(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>

7 个答案:

答案 0 :(得分:5)

您在两个标签中使用title类,这意味着它在两个广播框中都使用。单击它时,它会在两个单选框上触发事件。您应该使用单选按钮选择器来完成工作:

$(document).ready(function () {
    $(":radio").on("change", function (event) {
        alert('clicked');
    });
});

demo

参考change

点击

$(document).ready(function () {
    $(":radio").on("click", function (event) {
        alert('clicked');
    });
});

<强> demo

答案 1 :(得分:1)

尝试

$(".title input").on("click", function (event) {
  alert('clicked');
});

答案 2 :(得分:0)

问题是来自<label>,因为当您点击标签时,也会点击广播,反之亦然。 如果您将<label>更改为<p>,则会解决此问题:DEMO HERE

<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>

或者只是尝试将click事件添加到这样的输入:

$(document).ready(function () {
    $(".title input[type='radio']").on("click", function (e) {
        alert('clicked');
    });
});

答案 3 :(得分:0)

使用更改事件。它会正常工作。

$(document).ready(function () {
    $(".title").on("change", function (event) {
        alert('clicked');
    });
});

答案 4 :(得分:0)

这是因为您的<input>标记位于<label>标记内;因为点击标签也会触发收音机上的点击,你基本上是两次点击收音机。

如果您将<input>标记移出<label>标记,则应该没问题。

答案 5 :(得分:0)

这与我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');
        });
    });

Fiddle

答案 6 :(得分:-1)

进行了一些修改并且工作正常......虽然您的代码是正确的,但 example

    $(document).ready(function () {
        $("input[type=radio]").on("click", function (event) {
            alert('clicked');
        });
    });
相关问题