gpt4 book ai didi

javascript - JS在函数中创建全局变量并在另一个函数中使用它

转载 作者:行者123 更新时间:2023-12-03 00:41:44 25 4
gpt4 key购买 nike

我无法在函数中创建全局变量

function getFabrics(){
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "af_general.php?action=fabrics", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
fabrics_json=JSON.parse(this.responseText);
console.log(fabrics_json);
}
};
}

并在另一个中使用它:

function addrow(){
getFabrics();
var table=document.getElementById('stoixeia');
var rows = table.getElementsByTagName("tr").length;
var row = table.insertRow(-1);
var cell1 = row.insertCell(-1);
var rowno=rows-1;
var pcs_ent=document.createElement('input');
setAttributes(pcs_ent,{'type':'number','id':'pcs.'+rowno,'name':'pcs','style':'width: 4em;text-align:right','min':'0','max':'99','autocomplete':'off'});
cell1.innerHTML='#'+rowno;
cell1.appendChild(pcs_ent);
var cell2 = row.insertCell(-1);
var fabric_ent=document.createElement('select');
console.log(fabrics_json);//returns undefined
for (f in fabrics_json){
option = document.createElement('option');
option.value=fabrics_json[f][0];
option.text=fabrics_json[f][1];
fabric_ent.add(option);
}
//and goes on...
}

我已经阅读了 stackoverflow 中所有可能的问题,但我找不到获得结果的方法。无论我是否在脚本开头声明,fabrics_json 都保持未定义状态。

最佳答案

JavaScript 中的全局变量是 window 对象的成员。将全局变量引用为 window.fabrics_json

如果两个函数位于同一个源文件中,您可以在全局范围内声明 var Fabrics_json; 并使用或不使用 window. 前缀来访问它。

关于javascript - JS在函数中创建全局变量并在另一个函数中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428535/

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