我正在从事事件管理项目。我在 1 天内创建了一个事件。我想仅当用户单击空白部分时更改 td 的背景颜色。如果他们点击事件 div,背景颜色应该不会发生变化。
$(document).on("click", "td", function() {
$(this).css("background-color", "lightblue");
});
如果我单击该事件,背景颜色会发生变化。我希望它仅在我单击空白部分时发生变化。
最佳答案
要实现此目的,您可以检查 event.target
是否与事件绑定(bind)到的元素匹配。试试这个:
$(document).on("click", "td", function(e) {
if (e.target == this)
$(this).css("background-color", "lightblue");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
Click me and the BG will change
<div>Click me and it won't</div>
</td>
</tr>
</table>
关于jquery单击空白部分时更改td的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58321218/