【发布时间】:2017-11-01 14:31:20
【问题描述】:
有两个类为.egg 的div。用户应该单击他们想要更改背景颜色的 div,然后单击 div 新背景的颜色。一共两步。我编写了一个 jQuery 函数来捕获为背景更改选择的 div 的 id,然后为要更改为背景的颜色捕获 id。效果很好,除了当新的div被选中时,为了改变背景颜色,之前选中的divid仍然存储在名为clickedId的变量中。
为了尝试解决这个问题,我在所选 div 的背景更改后设置了clickedId = '';。 However when a new div is selected, it doesn't work anymore.控制台显示Cannot read property 'style' of null。看起来代码的第一部分,$(".egg").click(function() {... 不会为新的 div 选择执行。
有没有人对此有任何建议或意见?提前致谢!
jQuery 代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//Select the div to change the background color
$(".egg").click(function() {
var clickedId = $(this).attr("id");
//Updating the background color for selected div
$(".color").click(function() {
var clickedColor = $(this).attr("id");
if(clickedColor == 'red'){
document.getElementById(clickedId).style.backgroundColor = "red";
clickedId = '';
return;
}else if(clickedColor == 'blue'){
document.getElementById(clickedId).style.backgroundColor = "blue";
clickedId = '';
return;
}else if (clickedColor == 'yellow') {
document.getElementById(clickedId).style.backgroundColor = "yellow";
clickedId = '';
return;
}else{
document.getElementById(clickedId).style.backgroundColor = "white";
clickedId = '';
return;
}
});
});
});
</script>
HTML 代码:
<body>
<div id="egg-main">
<div id="left-egg"></div>
<div id="center-egg1" class="egg" onclick="semi_left()"></div>
<div id="center-egg2" class="egg" onclick="semi_right()"></div>
<div id="right-egg"></div>
<div id="bottom">
<div id="red" class="color"></div>
<div id="blue" class="color"></div>
<div id="yellow" class="color"></div>
<div id="white" class="color"></div>
</div>
</div>
<script src="demo.js"></script>
</body>
【问题讨论】:
-
为什么?您已经知道您所在的元素 - 为什么还要再次以不同的方式更改颜色?
标签: javascript jquery