【问题标题】:jQuery Get Dropdown Selection from Passed-in Parameter (ID) [duplicate]jQuery从传入的参数(ID)获取下拉选择[重复]
【发布时间】:2014-01-30 20:13:38
【问题描述】:

我的页面上生成了一系列下拉列表,如下所示。

<select id="opt(1)">
  <option value="Edit">Edit</option>
  <option value="View">View</option>
</select>

<select id="opt(2)">
  <option value="Edit">Edit</option>
  <option value="View">View</option>
</select>


<select id="opt(3)">
  <option value="Edit">Edit</option>
  <option value="View">View</option>
</select>

等等

我需要编写一个 JavaScript 函数,该函数将使用 jQuery 返回基于索引的下拉列表的当前选择,该索引是 ID 的一部分。

function getDropdownSelection(index) {

var sel = $('#opt(' + index + ') :selected').text();
alert(sel);
}

这不起作用。问题是: 1)如何转义ID中的() 2) 如何在 $('..') 中传入参数值。

谢谢

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您可以执行以下操作

为所有下拉菜单添加一个类名

<select class="test" id="opt(1)">
..
</select>
<select class="test" id="opt(2)">
..
</select>

那么jQuery应该是:

$(".test").on("change", function(){
    alert($(this).attr("id"));
});

希望对你有帮助!!

【讨论】:

  • 谢谢,但我必须在 ID 上使用 jQuery 选择语法。
【解决方案2】:

我解决了:

function getDropdownSelection(index) {

var sel = $('#opt\\(' + index + '\\) :selected').text();
alert(sel);
}

【讨论】:

    【解决方案3】:

    你是说这个吗?

    $(function() {
        $("[id^=opt]").on('change', function(){
            var id = this.id;
            /* Do something */
        }); 
    });
    
    • 选择器[id^=opt] 表示startsWith,将得到所有匹配的elements。在这种情况下,您的 html select(s)。然后,您可以做其他事情而无需创建额外的 functions

    另一种方法

    $(function() {
        $("[id^=opt]").on('change', function(){
            var selTxt = $('option:selected', this).text();
        });
    });
    
    • 通过这种方式,您可以从selected 选项中获得您所请求的text(不是value

    PS。我真的不知道你为什么越来越复杂。

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2013-07-05
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多