由于某种原因,我无法更新userPickColor的值,该值始终未定义。但是我尝试在这些函数中使用console.log,并且我的值实际上正在更改。但是由于某些原因,一旦我在函数外部调用它,它根本就不会更新。我还是Java语言的新手,请帮助我
这是我的代码:
var white = document.getElementById("white");
var black = document.getElementById("black");
var userPickColor;
white.addEventListener("click", whiteshirt);
black.addEventListener("click", blackshirt);
function whiteshirt(){
userPickColor= "white";
}
function blackshirt(){
userPickColor= "black";
}
ShirtDescrp.innerHTML = userPickColor;
正如其他人所说,您需要放置用于更新.innerHTML
回调函数内部的行,以便在更新变量之后,也可以使用最新的变量值来更新页面。
但是,将这一步骤更进一步...有一种称为DRY(不要重复自己)的通用编码方法,您有两个回调函数在很大程度上完成相同的工作。唯一的区别是设置的实际文本。单击页面上的两个元素之一并且这两个元素具有要用作其文字的文本时,这两个函数将运行id
。我们可以很容易地将两个回调合并为一个这样的回调:
var ShirtDescrp = document.getElementById("des");
// There's nothing wrong with variables if they help you read the code
// more easily, but if you won't be using the value they store more than
// once, they don't really add much.
document.getElementById("white").addEventListener("click", changeColor);
document.getElementById("black").addEventListener("click", changeColor);
function changeColor() {
// No variable needed. Just set the text to the id of the element that got clicked
// "this" here refers to the object that initiated the call for the current function
// which will be one of the two buttons.
ShirtDescrp.innerHTML = this.id;
}
<button id="white">white</button>
<button id="black">black</button>
<p id="des"></p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句