我正在开发一个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>
答案 0 :(得分:2)
您需要使用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>