html div onclick 事件 [英] html div onclick event

查看:22
本文介绍了html div onclick 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,

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

js代码

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

function markActiveLink(el) {   
    alert($(el).attr("id"));
} 

在这里,当我单击 div 时,我收到了 123 消息的警报,这很好,但是当我单击 ABC 时,我想要消息 I想调用 markActiveLink 方法.

here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.

JSFiddle

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

what is wrong with my code? please help me out.

推荐答案

问题是点击锚点仍然触发了你的 <div> 中的点击.这就是所谓的事件冒泡".

The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

其实有多种解决方案:

  • 在 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"));
});

  • 从锚点点击监听器停止事件传播
    →jsFiddle

    $("#ancherComplaint").click(function (evt) {
        evt.stopPropagation();
        alert($(this).attr("id"));
    });
    


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


    As you may have noticed, I have removed the following selector part from my examples:

    :not(#ancherComplaint)
    

    这是不必要的,因为没有类 .expandable-panel-heading 的元素也有 #ancherComplaint 作为其 ID.

    This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

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

    I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

    这篇关于html div onclick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆