Javascript jQuery:根据文本设置选择列表“已选择”,奇怪地失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3644449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Setting select list 'selected' based on text, failing strangely
提问by Stuart Allen
I have been using the following code (with jQuery v1.4.2) to set the 'selected' attribute of a select list based on its 'text' description rather than its 'value':
我一直在使用以下代码(使用 jQuery v1.4.2)根据其“文本”描述而不是“值”设置选择列表的“selected”属性:
$("#my-Select option[text=" + myText +"]").attr("selected","selected") ;
This code worked fine, until I noticed one select list on which it failed, depending on the text that was being matched. After some hair-pulling I realized that it was failing only in cases where the text was a single word (no spaces, no non-alpha characters). (All of my previous uses of this code had worked fine with select lists comprised solely of multi-word chemical names.)
这段代码运行良好,直到我注意到它失败的一个选择列表,这取决于匹配的文本。经过一番梳理之后,我意识到只有在文本是单个单词(没有空格,没有非字母字符)的情况下才会失败。(我之前对这段代码的所有使用都适用于仅由多词化学名称组成的选择列表。)
For example, within the one select list, it worked fine with:
pharbitic acid
25-D-spirosta-3,5-diene
pogostol (#Pogostemon#)
例如,在一个选择列表中,它适用于:
pharbitic acid
25-D-
spirosta -3,5-diene pogostol (#Pogostemon#)
It failed with:
glucose
adenine
它失败了:
葡萄糖
腺嘌呤
I have tried any way I could think of to surround the text variable with quotes (both single and double) to no avail. (But why should a single word need quotes when a two word phrase does not?)
我已经尝试过任何我能想到的用引号(单引号和双引号)包围文本变量的方法都无济于事。(但是为什么一个单词需要引号,而两个单词的短语不需要呢?)
I have tried hard coding the text in there and had the same result.
我已经尝试在那里对文本进行硬编码并得到了相同的结果。
This works:
这有效:
$("#constituent option[text=#a#-allocryptopine]").attr('selected', 'selected');
This works:
这有效:
$("#constituent option[text=5-O-methylrisanrinol]").attr('selected', 'selected');
This did not work:
这不起作用:
$("#constituent option[text=adenine]").attr('selected', 'selected');
I tried hard coding quotes. This did not work:
我尝试硬编码引号。这不起作用:
$("#constituent option[text='glucose']").attr('selected', 'selected');
I could not get hard coded quotes (single or double) to work with anytext at all.
我根本无法使用硬编码引号(单引号或双引号)来处理任何文本。
It's worth noting that quotes are acceptable when using the 'value' attribute. E.g., both of these work fine:
值得注意的是,在使用 'value' 属性时可以接受引号。例如,这两个都可以正常工作:
$("#constituent option[value='3']").attr('selected', 'selected');
$("#constituent option[value=3]").attr('selected', 'selected');
Below is some code to demonstrate the problem. Two select lists, the first of which is comprised of simple words, the second of two word phrases. When the page loads it tries to set the value of each select list. The jQuery code works for the second list but not the first. (I tried putting a space in 'monkey' to get 'mon key' and it worked!)
下面是一些代码来演示这个问题。两个选择列表,第一个由简单的单词组成,第二个由两个单词短语组成。当页面加载时,它会尝试设置每个选择列表的值。jQuery 代码适用于第二个列表,但不适用于第一个。(我尝试在 'monkey' 中放置一个空格来获取 'mon key' 并且成功了!)
A working demo of the code below is here.
下面代码的工作演示在这里。
I would greatly appreciate any insight into what I am doing wrong here. Or even an alternative selector syntax for using the 'text' attribute. Thanks in advance to all who have the time to assist.
我将不胜感激对我在这里做错了什么的任何见解。或者甚至是使用 'text' 属性的替代选择器语法。提前感谢所有有时间提供帮助的人。
<!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>
回答by Nick Craver
When an <option>isn't given a value="", the text becomes its value, so you can just use .val()on the <select>to set by value, like this:
当 an<option>未给出 a 时value="",文本变为 its value,因此您可以仅使用.val()on<select>按值设置,如下所示:
var text1 = 'Monkey';
$("#mySelect1").val(text1);
var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);
You can test it out here, if the example is notwhat you're after and they actually have a value, use the <option>element's .textproperty to .filter(), like this:
您可以在此处进行测试,如果示例不是您想要的并且它们实际上具有值,请使用<option>元素的.text属性 to .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);?
回答by Deivide
$("#my-select option:contains(" + myText +")").attr("selected", true);
This returns the first option containing your text description.
这将返回包含您的文本描述的第一个选项。
回答by ScottE
try this:
尝试这个:
$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
回答by wsanville
回答by chepe263
In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript
如果有人为此使用谷歌,上面的解决方案对我不起作用,所以我结束了使用“纯”javascript
document.getElementById("The id of the element").value = "The value"
And that would set the value and make the current value selected in the combo box. Tested in firefox.
这将设置值并使当前值在组合框中选择。在火狐中测试。
it was easier than keep googling a solution for jQuery
这比继续谷歌搜索 jQuery 解决方案更容易
回答by Ly Thanh Ngo
I usually use:
我通常使用:
$("#my-Select option[text='" + myText +"']").attr("selected","selected") ;
回答by Matt
The following works for text entries both with and without spaces:
以下适用于带空格和不带空格的文本条目:
$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
回答by Kaushik Das
We can do it by searching the text in options of dropdown list and then by setting selected attribute to true.
我们可以通过在下拉列表的选项中搜索文本,然后将 selected 属性设置为 true 来实现。
This code is run in every environment.
此代码在每个环境中运行。
$("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');
回答by ash
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;
},
回答by Chirag Prajapati
If you want to selected value on drop-down text bases so you should use below changes: Here below is example and country name is dynamic:
如果要在下拉文本库中选择值,则应使用以下更改:以下是示例,国家/地区名称是动态的:
<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>

