jquery单击空白部分时更改td的背景颜色

标签 jquery html-table

我正在从事事件管理项目。我在 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/

相关文章:

javascript - 将动态json添加到静态json

jquery - 标记为图像

javascript - jQuery Serialize 与 Bootstrap 单选按钮组间歇性工作

javascript - 无法弄清楚如何在我的网页中实现以下 jQuery 插件

html - 表格单元格中的文本应仅在悬停时换行,否则应以省略号结尾

javascript - 在 JavaScript 中将一系列 DOMNodeInserted 事件作为单个事件处理

html - CSS 样式表 tds

html - 每行的列数不同

python - 使用 python/beautifulsoup 抓取没有 id 的表,如何使用文本 html 字符串?

基于 HTML 表格的游戏中的 Javascript 函数