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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:30:46  来源:igfitidea点击:

Get inner html of the selected option

javascriptdom

提问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].textreturns 'test 1'
  • document.getElementsByTagName('select')[0].options[0].innerHTMLreturns 'test 1'
  • document.getElementsByTagName('select')[0].options[0].firstChildreturns a text node containing 'test 1'
  • document.getElementsByTagName('select')[0].firstChild.nextSiblingreturns 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”