【问题标题】:button click event triggering wrong event handler按钮单击事件触发错误的事件处理程序
【发布时间】:2012-12-13 21:45:28
【问题描述】:

我有一个 div 显示一些可点击的音乐标题。当您单击它时,它将显示更多详细信息。然后我在可点击的 div 中也有一个按钮。当我点击按钮时。它不会调用按钮的功能而是div的功能?有没有办法解决这个问题?谢谢!

$("#myComList").append("<div id="+comListID+" class=listDiv> <p class=comTitle><? echo $row["compositionTitle"] ?>(<?echo $row["year"]?>)</p><button id="+comListID+"btn class=addNewArrBtn>Add new Arrangement</button> <p class=comOri>BY <? echo $row["OrigComposer"] ?></p> </div>");
        $('#'+comListID).click(function() {
              $(this).find("li").slideToggle('slow', function() {
            });
        $("#"+comListID+"btn").click(function(){
                addNewArr(comListID);
            });

【问题讨论】:

  • 我为这部分添加了我的代码

标签: javascript jquery html button


【解决方案1】:

这叫做“冒泡”。该按钮位于 div 内,因此它正在执行按钮,然后沿着链向上到达 div。在按钮函数中添加 event.stopPropagation()。

$("#"+comListID+"btn").click(function(event){
    event.stopPropagation();
    addNewArr(comListID);
});

【讨论】:

  • 方法拼写为“stopPropagation”。
【解决方案2】:

来自 jQuery 文档:

默认情况下,大多数事件会从原始事件目标冒泡到 文档元素。在沿途的每个元素, jQuery 调用任何已附加的匹配事件处理程序。 处理程序可以防止事件在文档中进一步冒泡 树(从而阻止这些元素上的处理程序运行)通过 调用 event.stopPropagation()。附加在 但是,当前元素将运行。为防止这种情况,请致电 event.stopImmediatePropagation()。 (绑定到元素的事件处理程序 调用的顺序与它们绑定的顺序相同。)

http://api.jquery.com/on/

所以你会在按钮点击处理程序中调用event.stopPropagation(),以阻止 div 事件触发。

【讨论】:

    【解决方案3】:

    我相信我在没有看到代码的情况下理解了您的问题。听起来问题源于点击事件冒泡或传播。下面是一个可供尝试的代码示例和一个指向小提琴的链接供您测试:

    <div id="testDiv" onclick="alert('Stop Clicking Me!');">
        <button type="button" onclick="function(e) { alert('You hit the button!'); e.stopPropagation(); }">Click Me!</button>
    </div>
    

    在这个函数中:

    e.stopPropagation();
    

    防止点击事件过滤到其父容器(在本例中为“testDiv”)并触发其点击事件。您可以在下面的 jsfiddle 中对其进行测试并亲自查看:

    Test Fiddle

    编辑:

    在你的情况下:

    $("#"+comListID+"btn").click(function(e){
        addNewArr(comListID);
        e.stopPropagation();
    });
    

    将事件参数添加到点击函数并阻止它传播到父级。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-07
      • 2020-04-29
      • 2012-03-22
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多