gpt4 book ai didi

Javascript,selectedIndex 属性返回 [object HTMLSelectElement] + 值

转载 作者:行者123 更新时间:2023-11-28 19:17:15 25 4
gpt4 key购买 nike

我有简单的代码来获取下拉列表列表项的并将其写入到文档中。

Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>

<button type="button" onclick="myFunction()">Display index</button>

<script>
function myFunction() {
var x = document.getElementById("mySelect");
x += x.options[x.selectedIndex].value;
document.write("<br / >" + x);
}
</script>

我在这里面临两个问题,一个是结果[object HTMLSelectElement]+value。为什么会发生这种情况?

第二个是 document.write 属性删除了所有 body 元素并仅显示其结果。为什么会发生这种情况?能详细解释一下吗?

最佳答案

var x = document.getElementById("mySelect");
x += x.options[x.selectedIndex].value;
document.write("<br / >" + x);

您要将值附加到 x,它实际上是 HTMLSelectElement 类型的节点。

相反,它应该是:

var x = document.getElementById("mySelect"),
selectedValue = x.value;
document.write("<br / >" + selectedValue);

即使您不需要使用 selectedIndex 等,如果您只使用 document.getElementById("mySelect").value 它也会给出选定的值。

关于document.write,我建议您引用 MDN docs

您必须使用 appendChildinnerHTML,而不是 document.write。

function myFunction() {
var x = document.getElementById("mySelect"),
selectedValue = x.value;
document.querySelector("#result").innerHTML = selectedValue;
}
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<div id="result"></div>
<button type="button" onclick="myFunction()">Display index</button>

关于Javascript,selectedIndex 属性返回 [object HTMLSelectElement] + 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29587125/

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