【问题标题】:Obtaining the text from a drop-down box? [duplicate]从下拉框中获取文本? [复制]
【发布时间】:2012-10-25 21:03:31
【问题描述】:

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

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>

谢谢

【问题讨论】:

标签: javascript jquery dom client-side-scripting


【解决方案1】:

试试

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

DEMO

【讨论】:

  • 谢谢你,这就是我一直在寻找的很棒的好作品和非常快的回报!
  • 一个option DOM 对象确实有一个text 属性,所以.text 也应该在这里工作:var text = tester.options[​​​tester.selectedIndex].text;
【解决方案2】:

Text looks good to me - jsFiddle

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

【讨论】:

    【解决方案3】:

    我想你想要这样的东西:

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

    (这是未经测试的,但您的答案应该与此类似)

    【讨论】:

      猜你喜欢
      • 2010-09-05
      • 2015-11-03
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2011-08-18
      • 2013-07-05
      • 2016-07-28
      • 2011-05-01
      相关资源
      最近更新 更多