gpt4 book ai didi

javascript - 具有事件监听器后变量不更新

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:43 24 4
gpt4 key购买 nike

出于某种原因我无法更新 userPickColor 的值,它始终未定义。但是我尝试在函数内部使用 console.log,我的值实际上在改变。但是由于某些原因,一旦我在函数外调用它,它就根本不会更新。我还是 Javascript 的新手所以请帮助我

这是我的代码:

 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 的行放在回调函数中,以便在更新变量后,您可以使用最新变量更新页面值(value)也是如此。

但是,更进一步……有一种称为 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>

关于javascript - 具有事件监听器后变量不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com