【问题标题】:jQuery: Setting select list 'selected' based on text, failing strangelyjQuery:根据文本设置选择列表“选择”,奇怪地失败了
【发布时间】:2011-04-08 08:24:58
【问题描述】:

我一直在使用以下代码(使用 jQuery v1.4.2)根据其“文本”描述而不是“值”来设置选择列表的“选定”属性:

$("#my-Select option[text=" + myText +"]").attr("selected","selected") ;

这段代码运行良好,直到我注意到它失败的一个选择列表,这取决于正在匹配的文本。经过一番拉扯后,我意识到它仅在文本是单个单词(没有空格,没有非字母字符)的情况下才会失败。 (我之前对该代码的所有使用都适用于仅由多词化学名称组成的选择列表。)

例如,在一个选择列表中,它适用于:
邻苯二甲酸
25-D-spirosta-3,5-二烯
pogostol (#Pogostemon#)

它失败了:
葡萄糖
腺嘌呤

我尝试了任何我能想到的方法来用引号(单引号和双引号)包围文本变量,但无济于事。 (但是为什么一个单词需要引号,而两个单词的短语不需要引号呢?)

我已经尝试对其中的文本进行硬编码,结果相同。

这行得通:

$("#constituent option[text=#a#-allocryptopine]").attr('selected', 'selected');

这行得通:

$("#constituent option[text=5-O-methylrisanrinol]").attr('selected', 'selected');

这不起作用:

$("#constituent option[text=adenine]").attr('selected', 'selected');

我尝试了硬编码引号。这不起作用:

$("#constituent option[text='glucose']").attr('selected', 'selected');

我根本无法使用硬编码引号(单引号或双引号)来处理任何文本。

值得注意的是,使用 'value' 属性时可以使用引号。例如,这两个都可以正常工作:

$("#constituent option[value='3']").attr('selected', 'selected');

$("#constituent option[value=3]").attr('selected', 'selected');

下面是一些演示问题的代码。两个选择列表,第一个由简单的单词组成,第二个由两个单词短语组成。当页面加载时,它会尝试设置每个选择列表的值。 jQuery 代码适用于第二个列表,但不适用于第一个。 (我尝试在 'monkey' 中放置一个空格来获得 'mon key' 并且成功了!)

下面代码的工作演示是here。

如果我能深入了解我在这里做错了什么,我将不胜感激。甚至是使用“文本”属性的替代选择器语法。提前感谢所有有时间提供帮助的人。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 

<head>

  <script type="text/javascript" src="../js/jquery/jquery.js"></script>

  <script type="text/javascript">

  $(document).ready(function(){

    var text1 = 'Monkey';
    $("#mySelect1 option[text=" + text1 + "]").attr('selected', 'selected');

    var text2 = 'Mushroom pie';
    $("#mySelect2 option[text=" + text2 + "]").attr('selected', 'selected');        

  });

  </script> 

</head>

<body>

  <select id="mySelect1">
    <option></option>
    <option>Banana</option>
    <option>Monkey</option>
    <option>Fritter</option>
  </select> 

  <select id="mySelect2">
    <option></option>
    <option>Cream cheese</option>
    <option>Mushroom pie</option>
    <option>French toast</option>
  </select> 

</body>

</html>

【问题讨论】:

  • 您是否有理由不能简单地设置列表的选定索引?根据文本值进行选择并不是最好的方法。
  • 我明白你的意思,但我不知道当时的索引值。基本上我从数据库构建一个数据表,用户可以通过单击它来编辑一行,下面的许多选择列表都填充了表中的值(这就是我使用上面的代码的目的)。可以从一个或多个列表中选择不同的值,然后使用 $.ajax 更新数据库和表。选择列表索引值是来自数据库表的 id 值。从理论上讲,我可以将这些与文本描述一起不可见地存储在表格中,但我会尽可能减少开销。

标签: javascript jquery


【解决方案1】:

当&lt;option&gt; 没有被赋予value="" 时,文本变成它的value,所以你可以在&lt;select&gt; 上使用.val() 来按值设置,如下所示:

var text1 = 'Monkey';
$("#mySelect1").val(text1);

var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);

You can test it out here,如果示例不是您所追求的,并且它们实际上具有值,请使用&lt;option&gt; 元素的.text 属性到.filter(),如下所示:

var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
    return this.text == text1; 
}).attr('selected', true);

var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
    return this.text == text2; 
}).attr('selected', true);​

You can test that version here.

【讨论】:

  • 非常感谢您的快速回复。正是我所追求的。 (事实上​​,我确实在实际代码中设置了值。)如果有人知道为什么我的原始代码在特定情况下似乎失败了,我仍然会非常感兴趣......
  • @Snubian - 大小写正确吗?匹配将区分大小写
  • 我很肯定外壳没问题,代码只有在我试图描述的非常特定的情况下才会失败。而且我已经用上面描述的硬编码值进行了测试。我的测试代码中“猴子”示例的失败似乎表明这种用法在某些情况下会失败。在jsFiddle上运行代码,你可以看到你只是在“Mon key”中放了一个空格,无论是text1变量还是list选项,都突然起作用了。
  • +1 我需要匹配选项值而不是标签文本。它是通过return this.val() == text2; 实现的
  • 现代读者应该注意这个答案已经过时了;在 jQuery 1.9+ 中使用 .attr('selected', true); 将失败,并且自 jQuery 1.6 起已被弃用。您应该改用.prop('selected', true)。见stackoverflow.com/a/496126/1709587
【解决方案2】:
$("#my-select option:contains(" + myText +")").attr("selected", true);

这将返回包含您的文本描述的第一个选项。

【讨论】:

    【解决方案3】:

    试试这个:

    $("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
    

    【讨论】:

      【解决方案4】:

      使用filter() 函数似乎适用于您的测试用例(在Firefox 中测试)。 选择器看起来像这样:

      $('#mySelect1 option').filter(function () {
          return $(this).text() === 'Banana';
      });
      

      【讨论】:

        【解决方案5】:

        我通常使用:

        $("#my-Select option[text='" + myText +"']").attr("selected","selected") ;
        

        【讨论】:

        • 这似乎有效,我赞成,但它不起作用!
        【解决方案6】:

        如果有人为此谷歌,上面的解决方案对我不起作用,所以我结束了使用“纯”javascript

        document.getElementById("The id of the element").value = "The value"
        

        这将设置值并在组合框中选择当前值。在 Firefox 中测试。

        这比继续在谷歌上搜索 jQuery 的解决方案要容易

        【讨论】:

          【解决方案7】:

          以下适用于带空格和不带空格的文本条目:

          $("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
          

          【讨论】:

            【解决方案8】:

            我们可以通过在下拉列表的选项中搜索文本,然后将 selected 属性设置为 true 来做到这一点。

            此代码在每个环境中运行。

             $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');
            

            【讨论】:

              【解决方案9】:
              setSelectedByText:function(eID,text) {
                  var ele=document.getElementById(eID);
                  for(var ii=0; ii<ele.length; ii++)
                      if(ele.options[ii].text==text) { //Found!
                          ele.options[ii].selected=true;
                          return true;
                      }
                  return false;
              },
              

              【讨论】:

              • 请您添加一些文本(不仅仅是代码块)
              【解决方案10】:

              如果您想在下拉文本库中选择值,那么您应该使用以下更改: 以下是示例,国家名称是动态的:

                  <select id="selectcountry">
                  <option value="1">India</option>
                  <option value="2">Ireland</option>
                  </select>
                  <script>
                   var country_name ='India'
                   $('#selectcountry').find('option:contains("' + country_name + '")').attr('selected', 'selected');
                  </script>
              

              【讨论】:

                【解决方案11】:

                我尝试了其中的一些东西,直到我找到了一个同时在 Firefox 和 IE 中工作的东西。这就是我想出的。

                $("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
                

                以更易读的方式编写它的另一种方式:

                var valofText = $("#my-Select" + " option").filter(function() {
                    return this.text == myText
                }).val();
                $(ElementID).val(valofText);
                

                伪代码:

                $("#my-Select").val( getValOfText( myText ) );
                

                【讨论】:

                • 这个答案似乎与其他答案没有任何明显的不同,包括更简洁的接受的答案。
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-09-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多