【问题标题】:Fetch selected item of DropDownList using $(this) object使用 $(this) 对象获取 DropDownList 的选定项
【发布时间】:2015-08-31 03:13:01
【问题描述】:

如何使用 $(this) 获取 DropDownList 的选定项?

我在一个网页中有两个 DropDownList。我想获取选定的项目名称。我尝试了 3 种方法,每种方法都给出了不同的结果。

  1. 此方法显示“第一个列表”中的选定项以及“第二个列表”中的选定项。我猜这是因为选择器的 ID 不合格。

  2. 此方法给出了正确的结果。我可以使用 $(this) 而不是 ID 来获得相同的结果吗?我猜这个对象将指向 html-element。

  3. 这个方法没有结果

    $(文档).ready( 功能() { $('#IdServerType').bind("change", LoadX); } );

。

function LoadX()
{
    var str = "";

    /////  1
    str = $("select option:selected").text(); 
    console.log('menu clicked: ' + str);

    /////  2
    str = $("#IdServerType option:selected").text();
    console.log('menu clicked: ' + str);

    /////  3
    str = $("this option:selected").text(); //3
    console.log('menu clicked: ' + str);
}

请注意,我希望将事件注册和事件处理程序分开;有助于代码维护。

【问题讨论】:

    标签: javascript jquery asp.net javascript-events


    【解决方案1】:

    您可以使用$(this) 和children() 来获取选定的option 元素。

    str = $(this).children("option:selected").text();
    

    children('option:selected') 将从select 元素中选择选定的option。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多