Javascript 获取所选选项的内部 html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5069294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get inner html of the selected option
提问by methodofaction
I have something like this:
我有这样的事情:
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
};
How can I get the innerHTML of the selected option in pure js? (no frameworks).
如何在纯js中获取所选选项的innerHTML?(没有框架)。
回答by Dr.Molle
Try:
尝试:
alert(this.options[this.selectedIndex].text);
Demo:
演示:
<select onchange="alert(this.options[this.selectedIndex].text)">
<option>foo
<option>bar
<option>foobar
</select>
回答by Matt Howell
This will work.
这将起作用。
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
};
回答by Brian Driscoll
I haven't tested it, but this might work:
我还没有测试过,但这可能有效:
alert(this.options[this.selectedIndex].innerHTML)
回答by Bryan Kyle
After doing some research it appears as though the browser (Chrome anyway) will strip out tags from option values making it impossible to get the actual HTML code. For example, given the following HTML:
在做了一些研究之后,似乎浏览器(无论如何是 Chrome)会从选项值中去除标签,从而无法获得实际的 HTML 代码。例如,给定以下 HTML:
<html>
<body>
<select>
<option><b>test 1</b></option>
<option><b>test 2</b></option>
</select>
</body>
</html>
document.getElementsByTagName('select')[0].options[0].text
returns 'test 1'document.getElementsByTagName('select')[0].options[0].innerHTML
returns 'test 1'document.getElementsByTagName('select')[0].options[0].firstChild
returns a text node containing 'test 1'document.getElementsByTagName('select')[0].firstChild.nextSibling
returns the first option node. Its first child is the text node 'test 1'
document.getElementsByTagName('select')[0].options[0].text
返回“测试 1”document.getElementsByTagName('select')[0].options[0].innerHTML
返回“测试 1”document.getElementsByTagName('select')[0].options[0].firstChild
返回一个包含“test 1”的文本节点document.getElementsByTagName('select')[0].firstChild.nextSibling
返回第一个选项节点。它的第一个子节点是文本节点“test 1”