以下是我尝试使用我的代码的内容:
这是我的JavaScript:
var lastOne;
function selection(event) {
event.target.style.width = "50px";
lastOne.style.width = "10px";
current = event.target.id;
lastOne = document.getElementById(current);
}
以下是相关的HTML:
<img src="images/Star.png" id="pic1" onclick="selection(event)">
<img src="images/Star.png" id="pic2" onclick="selection(event)">
目前,它正在编辑单击元素的宽度,但不对前一个元素执行任何操作。
答案 0 :(得分:5)
第一次调用selection
时,lastOne
尚未分配任何内容,并且JavaScript会抛出错误,并且此时将停止工作,因为lastOne
永远不会获得分配给任何东西。
var lastOne;
function selection(event) {
event.target.style.width = "50px";
//an error will get thrown on this line the first time the function is executed because lastOne has not been defined
lastOne.style.width = "10px";
current = event.target.id;
lastOne = document.getElementById(current);
}
我会通过这样做来解决这个问题:
var lastOne;
function selection(event) {
if(lastOne) {
lastOne.style.width = "10px";
}
event.target.style.width = "50px";
current = event.target.id;
lastOne = document.getElementById(current);
}
答案 1 :(得分:1)
除了一件事之外,一切正常:如果lastOne
变量没有值,则会发生错误,因此您必须检查此变量是否具有任何值。在你的情况下,if (lastOne) {//do stuff}
就足够了:
var lastOne;
function selection(event) {
event.target.style.width = "150px";
if (lastOne) {
lastOne.style.width = "50px";
}
current = event.target.id;
lastOne = document.getElementById(current);
}
&#13;
img {
width: 100px;
max-width: 150px;
height: auto;
}
&#13;
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Gold_Star.svg/2000px-Gold_Star.svg.png" id="pic1" onclick="selection(event)">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Gold_Star.svg/2000px-Gold_Star.svg.png" id="pic2" onclick="selection(event)">
&#13;