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
在它们之间显示空字符串而不是文本呢?
答案 0 :(得分:1)
现有特殊的API this.options[this.selectedIndex].text
。
innerText
是MDN
试试这个:
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;