为什么选项元素的innerText不显示?

时间:2016-06-06 12:58:20

标签: javascript

HTML

<label name="sel">choose your part</label>
<select id="sel">
<option></option>
<optgroup label="Part 1">
<option value="1">1</option>
<option value="2">2</option>
</optgroup>
<optgroup label="Part 2">
<option value="a">a</option>
<option value="b">b</option>
</optgroup>
</select>

JS

 var a = document.getElementById('sel');
 a.addEventListener('change',call_name,false) ;

 function call_name() {
  alert(this.innerText);
 } 

在警告框中,它是空白的,但是当我写this.value时,它会显示该选项的值。那么为什么this.innerText在它们之间显示空字符串而不是文本呢?

1 个答案:

答案 0 :(得分:1)

现有特殊的API this.options[this.selectedIndex].text

innerTextMDN

上所述的非标准化功能

试试这个:

&#13;
&#13;
var a = document.getElementById('sel');
 a.addEventListener('change',call_name,false) ;

 function call_name() {
  alert(this.options[this.selectedIndex].text);
 } 
&#13;
<label name="sel">choose your part</label>
<select id="sel">
  <option></option>
  <optgroup label="Part 1">
    <option value="1">1</option>
    <option value="2">2</option>
  </optgroup>
  <optgroup label="Part 2">
    <option value="a">a</option>
    <option value="b">b</option>
  </optgroup>
</select>
&#13;
&#13;
&#13;