我有以下 html 代码,在单击特定按钮时我想更改特定 html 元素的颜色。
<paper-button style="background:blue" class="blue"></paper-button>
<paper-button style="background:red" class="red"></paper-button>
这是我的脚本
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".blue, .red").click(function(){
$(".abc").css("background-color", $(".blue, .red").css("background-color"));
});
});
</script>
单击两个按钮时,该元素的颜色会发生变化,但会变为蓝色,不会变为红色。 当我将代码更改为
<paper-button style="background:red" class="red"></paper-button>
<paper-button style="background:blue" class="blue"></paper-button>
在这种情况下,无论按下什么按钮,颜色都会变为红色。 如何确保颜色随按下的按钮而变化。
最佳答案
执行此操作时,您正在使用 dom 中第一个元素的背景颜色 $(".blue, .red").css("background-color")
。使用 $(this)
仅获取被点击元素的背景颜色:
$(".blue, .red").click(function(){
$(".abc").css("background-color", $(this).css("background-color"));
});
关于javascript - Jquery 多次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32666117/