使用 $(this) 对象获取 DropDownList 的选定项目

Fetch selected item of DropDownList using $(this) object

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

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

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

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

  3. 此方法没有结果

    $(document).ready(
         function()
         {
              $('#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);
}

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

您可以将 $(this)children() 一起使用以获得 selected option 元素。

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

children('option:selected') 将 select 来自 select 元素的 selected option