javascript - 使用 jQuery 改变点击背景颜色

标签 javascript jquery html css

我是 jQuery 的新手,我已经通读了关于这个主题的线程,但是我在理解逻辑上遇到了一些困难,并且在重写我的代码之后,我仍然无法让它工作。

我有两个按钮,我希望每个按钮都能在单击时更改背景颜色和文本颜色。这是我的 jsfiddle 的链接

如有任何反馈或建议,我们将不胜感激。谢谢!

jQuery(document).ready(function() {
    $("#footer").on("click", "#purple', function() {
       $(this).css("background-color", "#9683ec");
       $(this).css("color", "#2d2746");
    });

    $("footer").on("click", "#blue', function() {
       $(this).css("background-color", "#00bfff");
       $(this).css("color", "#002633");
    });
});

最佳答案

Fiddle Demo

click 事件正在寻找 id#purple#blue 的后代,并且有在这两种情况下都不是一个。

来自 on 的 jQuery 文档功能:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

span 包裹按钮中的文本并在 span 上设置 id 值将起作用。

此外,您似乎没有针对点击事件的 body,因此 background-color 不会按预期更改。

HTML

<footer>
  <button><span id="purple">Purple</span></button>
  <button><span id="blue">Blue</span></button>
  <p>&copy;Allison Harris 2016</p>
</footer>

jQuery:

jQuery(document).ready(function() {
  $("button").on("click", "#purple", function() {
    $('body').css("background-color", "#9683ec");
  });

  $("button").on("click", "#blue", function() {
    $('body').css("background-color", "#00bfff");
  });
});

关于javascript - 使用 jQuery 改变点击背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35538319/

相关文章:

jquery - 上传带预览的多张图片

html - 奇怪的 CSS 类名,有人向我解释一下这是怎么回事吗?

javascript - 避免 FF JS 自动 HTML 编码?

math - 在给定三边的坐标平面中绘制三角形

javascript - 使用 Express js 在其帐户创建或注册表中上传用户图像

javascript - Angular 6 在 token 更新后重新制作请求之前更改 JWT token

javascript - 使用 "gulp-translate-html"和 "gulp-inject"时的 Gulp 管道和缓存问题

javascript - 添加类定义的不透明度不会影响 Webkit 中的元素

javascript - 我希望动画在事件状态下触发并在事件状态消失后继续

javascript - Instafeed js 在每 4 个图像周围添加包装