我有一个下拉菜单,我在onfocus
事件上动态添加选项(基于AJAX调用)。出于某种原因,我第一次点击这个框时,选项会缩小成一个小盒子,但第二次它工作得很好。有谁知道可能导致这种现象的原因是什么? (注意:因为它涉及AJAX,我无法插入可以模拟错误的小提琴,但我会发布代码本身)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Remove Class | IMS</title>
<link rel="stylesheet" type="text/css" href="../css/form.css"/>
</head>
<body>
<form>
<label for="class">Class:</label>
<select name="class" onfocus="loadClasses(this)" id="drop" required>
<option>Sample Value</option>
</select>
<hr/>
<button type="button" onclick="sendData()">Remove Class</button>
</form>
</body>
</html>
JS代码:
function genDrop(e, json) {
e.innerHTML = "";
var data = eval("({data: " + json + "})");
data = data.data;
for (var i = 0; i < data.length; i++) {
var option = data[i];
var o = document.createElement("option");
o.value = option.id;
o.innerHTML = option.name;
o.setAttribute("descript", option.descript);
o.style.width = "500px !important"
o.style.maxWidth = "200%";
e.appendChild(o);
}
}
function loadClasses(e) {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
genDrop(e, http.responseText);
}
}
http.open("GET", "getclasses.php", true);
http.send();
}
答案 0 :(得分:2)
使用onload代替onfocus
<select name="class" onload="loadClasses(this)" id="drop" required>
<option>Sample Value</option>
</select>