Javascript 获取所选选项的内部html
我有这样的想法:Javascript 获取所选选项的内部html,javascript,dom,Javascript,Dom,我有这样的想法: select = document.getElementById("select"); select.onchange = function(){ alert(this.value); //returns the selected value alert(this.innerHTML); //returns the entire select with all the options alert(this.selected.innerHTML); //this is
select = document.getElementById("select");
select.onchange = function(){
alert(this.value); //returns the selected value
alert(this.innerHTML); //returns the entire select with all the options
alert(this.selected.innerHTML); //this is what I want, but doesn't work, of course
};
如何在纯js中获取所选选项的innerHTML?(没有框架)。试试:
alert(this.options[this.selectedIndex].text);
演示:
福
酒吧
福巴
我还没有测试它,但这可能会起作用:
alert(this.options[this.selectedIndex].innerHTML)
在做了一些研究之后,浏览器(Chrome浏览器)似乎会从选项值中去掉标记,从而无法获得实际的HTML代码。例如,给定以下HTML:
<html>
<body>
<select>
<option><b>test 1</b></option>
<option><b>test 2</b></option>
</select>
</body>
</html>
测试1
测试2
返回“测试1”document.getElementsByTagName('select')[0]。选项[0]。文本
返回“测试1”document.getElementsByTagName('select')[0]。选项[0]。innerHTML
返回包含“测试1”的文本节点document.getElementsByTagName('select')[0]。选项[0]。firstChild
返回第一个选项节点。它的第一个子节点是文本节点“test1”document.getElementsByTagName('select')[0].firstChild.nextSibling
select = document.getElementById("select");
select.onchange = function(){
alert(this.value); //returns the selected value
alert(this.innerHTML); //returns the entire select with all the options
var options = this.getElementsByTagName("option");
var optionHTML = options[this.selectedIndex].innerHTML;
alert(optionHTML); //this is what I want, but it works now
};
我建议使用以下代码段:
alert(this.selectedOptions[0].text)
演示:
一
二
三
good call,使用没有库的js,一些IE浏览器不会将innerHTML或节点与选项关联。无需尝试:这是正确的,适用于90年代中期以来发布的所有主流浏览器。对你的答案有信心:)如果我的答案可能是错的,没有不确定性,但我不知道他喜欢对结果做什么。如果在选项中使用字符引用,则文本返回的结果可能不同于innerHTML,因此“try”更像是“try if you's search”:)我更喜欢文本。当我从异步GET请求中填写选项时,.innerHTML不起作用,但.text起作用。谢谢,我的意图是.text(我不知道它存在),但这很有趣。