如果用户点击了img
元素,则警告会显示test-image
和two-side-text
。但我需要只显示test-image
。我怎么能这样做?
$("body").on('click', 'td', function(evt) {
alert($(this).attr('class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="Two-side-text">
<table>
<tbody>
<tr>
<td class="test-image">
<img src="img-placeholder.png">
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td class="test-paragraph">
<p>
test paragraph
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
答案 0 :(得分:2)
您需要停止将DOM冒充到父td
元素的事件。为此,您可以在活动上致电stopPropagation()
,如下所示:
$(document).on('click', 'td', function(evt) {
evt.stopPropagation();
alert($(this).attr('class'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="Two-side-text">
<table>
<tbody>
<tr>
<td class="test-image">
<img src="img-placeholder.png">
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td class="test-paragraph">
<p>
test paragraph
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
&#13;