[英]Changing value of a global variable from the inside of function using input
I have a 我有一个
var imgSrc = false;
dom.getElByTag('img')[0].onclick = function(){
//set src of image
changeBool(dom.getElByTag('img')[0]);
}
function changeBool(n){
if(n.src ===="file/path"){
imgSrc = true;
};
console.log(imgSrc);
So the problem is that imgSrc is only changed locally in changeBool so if I console.log imgSrc it will return false, regardless of where I put it (this is likely because the page has already loaded and decided that imgSrc is false before I set it to true with the onclick, and since javascript runs one line at a time it has run console.log(imgSrc) as false before I could even click the image. 因此问题在于imgSrc仅在changeBool中进行了本地更改,因此如果我console.log imgSrc它将返回false,而不管我放置在哪里(这很可能是因为页面已经加载并在设置前确定imgSrc为false会随着onclick变为true,并且因为javascript一次只运行一行,所以我什至没有单击该图像就已经将console.log(imgSrc)作为false运行。
So, I need to: 因此,我需要:
declare a boolean as false -> click an image, which sets boolean as true -> console.logging the boolean (and seeing true) 将布尔值声明为false->单击图像,将布尔值设置为true-> console.loging布尔值(并看到true)
But what I am doing right now is: declare a boolean as false -> console.logging the boolean (and seeing false {because it hasn't been set to true yet} - > clicking an image and setting the boolean to true. 但是我现在要做的是:将布尔值声明为false-> console.logging布尔值(并看到false {因为尚未将其设置为true)->单击图像并将布尔值设置为true。
How can I fix this? 我怎样才能解决这个问题?
Just move your logging statement inside the changeBool
function like so: 只需将您的日志记录语句移动到changeBool
函数中,如下所示:
var imgSet = false;
dom.getElByTag('img')[0].onclick = function(){
//set src of image
changeBool(dom.getElByTag('img')[0]);
}
function changeBool(n){
if(n.src ===="file/path") imgSrc = true;
console.log(imgSrc);
};
In your first line of code, 在第一行代码中,
var imgSet = false;
Needs to be changed to 需要更改为
var imgSrc = false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.