html div onclick事件

Ani*_*vda 15 html javascript jquery onclick

我的jsp页面上有一个html div,我已经放了一个锚标记,请在下面找到代码,

<div class="expandable-panel-heading">
     <h2>
         <a id="ancherComplaint" href="#addComplaint" 
                            onclick="markActiveLink(this);">ABC</a>
     </h2>
</div>
Run Code Online (Sandbox Code Playgroud)

js代码

$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
     alert('123');
 });

function markActiveLink(el) {   
    alert($(el).attr("id"));
} 
Run Code Online (Sandbox Code Playgroud)

在这里,当我点击div时,我得到了警告123消息,它很好但是当我点击ABC我希望消息我想调用markActiveLink方法.

的jsfiddle

我的代码出了什么问题?请帮帮我.

Com*_*eek 18

问题是单击锚点仍会触发您的点击<div>.这被称为" 事件冒泡 ".

事实上,有多种解决方案:

  • 检查DIV单击事件处理程序是否实际目标元素是锚
    →jsFiddle

    $('.expandable-panel-heading').click(function (evt) {
        if (evt.target.tagName != "A") {
            alert('123');
        }
    
        // Also possible if conditions:
        // - evt.target.id != "ancherComplaint"
        // - !$(evt.target).is("#ancherComplaint")
    });
    
    $("#ancherComplaint").click(function () {
        alert($(this).attr("id"));
    });
    
    Run Code Online (Sandbox Code Playgroud)
  • 从锚点击侦听器→jsFiddle停止事件传播

    $("#ancherComplaint").click(function (evt) {
        evt.stopPropagation();
        alert($(this).attr("id"));
    });
    
    Run Code Online (Sandbox Code Playgroud)


您可能已经注意到,我已从示例中删除了以下选择器部分:

:not(#ancherComplaint)
Run Code Online (Sandbox Code Playgroud)

这是不必要的,因为类中没有元素.expandable-panel-heading也有#ancherComplaintID.

我假设您想要抑制锚点的事件.这不能以这种方式工作,因为两个选择器(你和我的)都选择完全相同的DIV.选择器在调用时对侦听器没有影响; 它只设置监听器应该注册的元素列表.由于此列表在两个版本中都相同,因此没有区别.