【问题标题】:Programmatically set the text of a select - jquery以编程方式设置选择的文本 - jquery
【发布时间】:2015-05-28 01:38:16
【问题描述】:

当我只知道选项的文本而不知道值时,我需要以编程方式设置现有选择框的选项。

这是我的代码:

$("#" + eventQuestions[x].code).find('option[text="' + eventAnswers[x].vAnswerString + '"]').attr("selected");

不要过分关注选择正确的 html 元素或 vAnswerString 中的正确文本 - 我可以确认这些是正确的。

基本上没有选择该选项。我的代码有什么问题?

【问题讨论】:

  • text选项的实际属性值,即<option text=something value=somethingElse>还是<option value=something>some text</option>,因为如果是第二种情况,您的选择器将不起作用
  • attr 函数在不提供第二个参数时返回属性的当前值。要添加选定的属性,请执行 $(**).attr("selected" , true)
  • 向您的选择器添加过滤器

标签: javascript jquery


【解决方案1】:

查看this的答案。

您可以使用该过滤器检查内部文本,然后像这样放置选定的属性:

.attr("selected", true);

我测试过的例子:

$(function() {
    $("#select").find("option").filter(function() {
        return this.innerHTML == "InnerText";
    }).attr("selected", true);
})

【讨论】:

    【解决方案2】:

    Here is a working example 用于 jquery 1.6+。

    使用过滤功能选择选项:

    var text = "theTextToFind";
    var matchingOption = $("select#myselect option").filter(function () {
            return $(this).text() == text;
        });
    

    使用属性函数设置值:

    matchingOption.prop('selected', true);
    

    也可以看看这个Answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 2013-02-05
      相关资源
      最近更新 更多