我试图让 SELECT 放弃它从这个 HTML 中获得的值,这是强加给我的。
从控制台来看,我似乎到达了页面上的正确位置,但是当尝试检查我是否在那里时,if = SELECT 没有返回正确的内容...
谁能帮忙...
感谢和问候
<div id="Select1" class="dingbats_form_entry">
<div class="dingbats_form_vertical_panel">
<div>
<div class="dingbats_form_label dingbats_form_label_top">Select1 </div>
<div class="dingbats_form_field list_container" style="width: 100px;">
<select class="gwt-ListBox dingbats_form_field_bottom" style="width: 135px;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
</div>
</div>
我的代码为
<script>
function isRealValue(obj) {
return obj && obj !== "null" && obj !== "undefined";
}
function getValue(ddl) {
try {
var obj = document.getElementById(ddl);
if (isRealValue(obj)) {
var lvl1 = obj.children;
console.log(lvl1);
var lvl2 = lvl1[0].children;
console.log(lvl2);
var lvl3 = lvl2[0].children;
console.log(lvl3);
var lvl4 = lvl3[1].children;
console.log(lvl4);
if (lvl4.tagName == 'SELECT') {
alert("FOUND IT!!");
}
try {
var val = obj.options[obj.selectedIndex].value;
} catch (err) {
window.alert("var val = obj.options[obj.selectedIndex].value " + err.message);
}
window.alert("myFunction: after Sel val: Indx" + ddl + " " + val);
document.getElementById("demo").innerHTML = val;
} else {
window.alert("obj is not a real object: " + ddl + " " + obj);
}
} catch (err) {
window.alert("var obj = document.getElementById(ddl) " + err.message);
}
}
if (document.getElementById("Select1")) {
document.getElementById("Select1").addEventListener("change", function () {
getValue("Select1");
});
} else {
window.alert("Select1 not found");
}
</script>
最佳答案
你离我们并不遥远。使用 getElementsByTagName() 来简化它并在每个阶段添加检查以避免不必要的 try/catch。下面的代码未经测试。
function getValue(ddl) {
var el = document.getElementById(ddl);
if (el) {
var selects = el.getElementsByTagName("select");
if (selects.length > 0) {
return selects[0];
if (select.selectedIndex >= 0) {
return select.value;
}
}
}
return null;
}
关于javascript - 获取div中select的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26405070/