Javascript选择属性的选项在任何方法中都不起作用
我面临一个奇怪的问题。请看清楚我的代码。 当我在js文件的根目录中调用下面的函数时,它工作得很顺利Javascript选择属性的选项在任何方法中都不起作用,javascript,node.js,select,bootstrap-4,Javascript,Node.js,Select,Bootstrap 4,我面临一个奇怪的问题。请看清楚我的代码。 当我在js文件的根目录中调用下面的函数时,它工作得很顺利 function setOptionValueWithNameAndOid(select, name, oid){ //here first parameter 'select' is my SELECT which is written in HTML and just pass the ID of that SELECT and 'name' and 'oid' is simple s
function setOptionValueWithNameAndOid(select, name, oid){
//here first parameter 'select' is my SELECT which is written in HTML and just pass the ID of that SELECT and 'name' and 'oid' is simple string
var option = document.createElement("option");
option.setAttribute("value", oid);
var textNode = document.createTextNode(name);
option.appendChild(textNode);
select.appendChild(option);
}
如果我在js文件体中调用这个函数
setOptionValueWithNameAndOid(select, name, oid)
因此,这是完美的工作。选择选项正在添加。
但当我在任何事件或任何函数内调用此函数时,就会出现问题
请仔细阅读此代码:
function loadNameOidSelect(url, select){
//here 'url' is my API url. and select is the same SELECT. just passing the id
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(dta => {
setOptionValueWithNameAndOid(select, dta.NAME, dta.OID); // from API i am getting 'name' and 'oid'
});
} else {
console.log('error');
}
}
request.send();
}
但现在的问题是,如果我在这个api中调用相同的方法,那么在我的SELECT中不会添加任何选项。
但是,如果我在页面加载中使用一些静态数据调用相同的方法,它就可以完美地工作
那么,您能帮我解决实际问题吗?您的评论说只传递id,但您的setOptionValueWithNameAndOid函数需要一个HTMLSelectElement对象。有控制台错误吗?我也传递HTMLSelectElement。没有控制台错误您在回调中尝试过console.logthis.response吗?输出是什么?