仅抓取所选元素,而不抓取父元素

时间:2018-10-22 15:28:26

标签: javascript jquery

我正在开发一个Web应用程序,该应用程序可获取您单击的元素的类。问题在于,下面的代码也同样获取了该元素的父类。我只需要所选元素的类。

$("*").click(function () {
    	var myClass = $(this).attr("class");
        alert(myClass);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="business">
  <div class="businesses"><h2 class="name">Name</h2><p>2484596322</p></div>
  <div class="businesses"><h2 class="name">Name</h2><p>2484596322</p></div>
  <div class="businesses"><h2 class="name">Name</h2><p>2484596322</p></div>
  <div class="businesses"><h2 class="name">Name</h2><p>2484596322</p></div>
  <div class="businesses"><h2 class="name">Name</h2><p>2484596322</p></div>
  <div class="businesses"><h2 class="name">Name</h2><p>2484596322</p></div>
</div>

1 个答案:

答案 0 :(得分:2)

Working fiddle

您需要使用e.stopPropagation()来阻止事件冒泡:

$("*").click(function(e) {
  e.stopPropagation();

  var myClass = $(this).attr("class");
  alert(myClass);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="business">
  <div class="businesses">
    <h2 class="name">Name</h2>
    <p>2484596322</p>
  </div>
  <div class="businesses">
    <h2 class="name">Name</h2>
    <p>2484596322</p>
  </div>
  <div class="businesses">
    <h2 class="name">Name</h2>
    <p>2484596322</p>
  </div>
  <div class="businesses">
    <h2 class="name">Name</h2>
    <p>2484596322</p>
  </div>
  <div class="businesses">
    <h2 class="name">Name</h2>
    <p>2484596322</p>
  </div>
  <div class="businesses">
    <h2 class="name">Name</h2>
    <p>2484596322</p>
  </div>
</div>