从下拉框中获取文本?

时间:2012-11-05 23:28:08

标签: javascript jquery dom client-side-scripting

这将获取我在下拉菜单中选择的任何内容的值。

document.getElementById('tester').value

但是,我无法找到下拉菜单当前显示的文本所需的属性。我尝试了“文本”,然后看了W3Schools,但没有答案,这里有人知道吗?

对于那些不确定的人,这是下拉框的HTML。

<select name="tester" id="tester">
    <option value="1">A skill</option>
    <option value="2">Another skill</option>
    <option value="3">Yet another skill</option>
</select>

由于

3 个答案:

答案 0 :(得分:3)

尝试

var tester = document.getElementById('tester');
var text = tester.options[​​​tester.selectedIndex].innerHTML​;

DEMO

答案 1 :(得分:1)

Text looks good to me - jsFiddle

$('#tester').on('change', function(){
    console.log($('option:selected', this).text()); 
});​

答案 2 :(得分:1)

我想你想要这样的东西:

var d = document.getElementById('tester');
var selected_text = d.options[d.selectedIndex].text;

(这是未经测试的,但你的回答应与此相似)