【问题标题】:jQuery :contains selector alternative? [duplicate]jQuery:包含选择器替代方案? [复制]
【发布时间】:2014-04-11 21:37:00
【问题描述】:

我想在下拉菜单中通过其'文本选择一个选项。当我运行代码时:

var theText = "Large"; $("#size option:contains(" + theText + ")").attr('selected', 'selected');

它选择 XLarge 而不是 Large。有没有办法让它选择大? JSFiddle:http://jsfiddle.net/r8wuP/2/

【问题讨论】:

标签: javascript jquery drop-down-menu


【解决方案1】:

您可以使用.filter() 查找完全匹配,:contains-selector 也返回部分匹配

var theText = "Large";
$("#size option").filter(function () {
    return $.trim($(this).text()) == theText;
}).attr('selected', 'selected');

演示:Fiddle

【讨论】:

  • 这个答案是正确的,所以Arun首先得到了正确答案:)
【解决方案2】:

试试这个:

http://jsfiddle.net/r8wuP/3/

$('#size').find('option').filter(function() {
    return $(this).text() === 'Large';
}).first().attr('selected', 'selected');

【讨论】:

    【解决方案3】:

    由于您使用的是 1.4,因此可以使用:

    var theText = "Large";
    $("#size").find("option[text='" + theText + "']").attr('selected', 'selected');
    

    不过以后的 jQuery 版本可能需要 filter 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-28
      • 2019-09-11
      • 1970-01-01
      • 2015-03-20
      • 2013-12-02
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多