繁体   English   中英

获取所选选项的内部 html

[英]Get inner html of the selected option

我有这样的事情:

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);

演示:

 <select onchange="alert(this.options[this.selectedIndex].text)"> <option>foo <option>bar <option>foobar </select>

我还没有测试过,但这可能有效:

alert(this.options[this.selectedIndex].innerHTML)

这将起作用。

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
};

在做了一些研究之后,似乎浏览器(无论如何是 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返回 '​​test 1'
  • document.getElementsByTagName('select')[0].options[0].innerHTML返回 '​​test 1'
  • document.getElementsByTagName('select')[0].options[0].firstChild返回一个包含“test 1”的文本节点
  • document.getElementsByTagName('select')[0].firstChild.nextSibling返回第一个选项节点。 它的第一个子节点是文本节点“test 1”

我建议使用这个片段:

alert(this.selectedOptions[0].text)

演示:

 <select onchange="alert(this.selectedOptions[0].text)"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select>

selectedOptions是一个 HTML 集合,其中包含所有选定的选项。 当您使用多选时,使用此代码段比this.options[this.selectedIndex]更有优势。 多选下拉列表的情况下, this.selectedOptions将包含所有选定的元素 您可以遍历此集合以获取所有选定项目的 innerHTML。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM