我是 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");
});
});
最佳答案
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>©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/