Javascript 在html中使用for时调用函数两次

Javascript 在html中使用for时调用函数两次,javascript,jquery,html,Javascript,Jquery,Html,下面的代码在单击单选名称而不是单选按钮时执行两次,如何停止该代码执行两次。如果我为删除,它将正常工作 HTML 单选按钮触发对li的单击 您可以直接在单选按钮上触发事件 $("#check").click(function (event) { alert(1); }); 或者,您可以检查事件目标是否为li $(".test").click(function (event) { // i don't know exactly what the condition will be

下面的代码在单击单选名称而不是单选按钮时执行两次,如何停止该代码执行两次。如果我为删除
,它将正常工作

HTML

单选按钮触发对li的单击

您可以直接在单选按钮上触发事件

$("#check").click(function (event) {

    alert(1);
});
或者,您可以检查事件目标是否为li

$(".test").click(function (event) {
    // i don't know exactly what the condition will be. Inspect the event.target to look at the property you want.
    if (event.target.html == "li")
    {
        alert(1);

    }
});
请尝试以下任一方法:

$(".test").click(function (event) {
    alert(1); 
    return false; //stops it from being handled a 2nd time
});

另一个选项是使用
change
而不是
单击

$(".test").change(function (event) {
    alert(1);  
});
要确认兹沃纳的评论,请尝试:

$(".test").click(function (event) {
    alert(1 + event.target);
});
它将被触发两次,一次用于
[object htmlabelelement]
,另一次用于
[object htmlinputeelement]

更新:A.Wollf是正确的,
返回false停止正在检查的单选按钮

<li class="test">
    <input type="radio" id="check" class="rd" name="v" value="1" />
    <label for="check">Radio 1</label>
</li>

此外,如果您只有一个可用选项,则没有理由使用单选按钮。请使用复选框

当单击单选按钮时,单击会冒泡到容器并触发另一次单击,因此您会看到它两次。根据您的使用情况,您可能不需要绑定到容器,而是绑定到单选按钮,可能在change
label for=“id”
上有一个单击单选按钮的内部浏览器机制。这导致它执行两次。@Huangism和zvona感谢您的快速回复,所以单击LI是否应该选中单选按钮?你预期的行为是什么?有没有愤怒的行为。。?刚才我走进办公室,爸爸。。我希望你能理解我(但是
返回false;
防止点击无线电标签的默认行为。+1为第二个;)@A.Wolff谢谢,没有注意到。例如:
如果($(event.target).is(':radio'))
刚刚看到,也许OP希望整个LI都可以点击,所以忘了我的评论吧,用firebug很容易找到,但我没有安装firefoxwork@MathieuLabrieParent出于好奇,你为什么不使用firefox呢?一些政策?是的,我在政府工作,我不是机器管理员。。。我们必须遵从他们的使用。我们有IE9,我甚至不能用小提琴测试css3和html5。
$(".test").change(function (event) {
    alert(1);  
});
$(".test").click(function (event) {
    alert(1 + event.target);
});
<li class="test">
    <input type="radio" id="check" class="rd" name="v" value="1" />
    <label for="check">Radio 1</label>
</li>
$("#check").click(function (event) { // You could change this to $(".rd") if you need to reuse it for other radio buttons
    event.stopPropagation();
    alert(1);
});