检测单击了哪个元素

时间:2016-04-25 06:04:25

标签: javascript jquery html

简而言之,我将本地HTML页面加载到asp.net中其他Web表单中的div

JQuery:

<script>
    $(function () {
        $("#includedContent").load("../HtmlHolder/index.html");
    });

</script>  

HTML:

  <div id="includedContent" class="WebHolder" style="width: 450px; height: 300px; border: 1px solid #808080; margin: 0px auto; overflow-y: scroll;"></div>

现在我想通过下面的脚本点击它们来获取元素的类名:

<script>
    $(document).ready(function () {
        $('.WebHolder').on("click", "*", function (e) {

            alert("Class :" + $(this).attr("class"));
        });
    });
</script>  

我的问题是,当我点击任何元素时,此代码会提醒此类名称并且它是父级!

如何解决?

注意:元素不是特定对象,可能是输入或按钮或textarea或....

2 个答案:

答案 0 :(得分:9)

您应该使用e.target将其用作选择器)而不是this因为它是父

alert("Class :" + $(e.target).attr("class"));

要避免对父级执行操作:您可以比较thise.target以验证它是否为父级。

if( this !== e.target )

演示代码:

&#13;
&#13;
$('div').on('click', function(e){

    if( this !== e.target ) alert( 'Class is '+ $(e.target).attr('class') );

});
&#13;
div{
  background: #fe7a15; 
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  
  I am the parent, Clicking me will not get you an alert but headers does, because they are my children.
  <br /><br />
  <h1 class="class-header-child-one">Header 1</h1>
  <h2 class="class-header-child-two">Header 2</h2>
  
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

在事件处理程序中使用event.stopPropagation()

$('.WebHolder').on("click", "*", function (e) {

    alert("Class :" + $(this).attr("class"));
    e.stopPropagation();
});

这将阻止事件冒泡DOM树。

<强>演示:

&#13;
&#13;
$(document.body).on('click', '*', function(e) {
    alert($(this).text());
    e.stopPropagation();
});
&#13;
div {
  background: red;
}
div > div {
  background: orange;
}
div > div > div {
  background: yellow;
}
div > div > div > div {
  background: gray;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Main
    <div>1
        <div>11</div>
        <div>12</div>
        <div>13
            <div>131</div>
        </div>
    </div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</div>
&#13;
&#13;
&#13;