获得“最新"消息.从多个选择列表中选择的选项的文本 [英] Getting the "newest" selected option's text from multiple select list
问题描述
我有一个HTML选择列表,其中可以有多个选择:
I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
我想每次选择时都得到一个选项的文本.我使用jQuery来做到这一点:
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
看起来很简单,但是如果选择列表已经有一些选择的选项-它也会返回其文本.例如,如果我已经选择了第二"选项,则在选择第四"之后,警报将为我带来第二".那么jQuery是否有任何简短的简单方法来仅获取当前"选定选项的文本,还是我必须使用字符串并过滤新文本?
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
推荐答案
您可以执行以下操作,保留旧的值数组并检查其中不存在哪个新值,例如:
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
});
在此处尝试,当您致电 $.inArray(val, arr) == -1
(如果未找到),则为新值.之后,我们仅使用属性等于选择器来抓取元素并得到它的 .text()
.
Give it a try here, When you call .val()
on a <select multiple>
it returns an array of the values of its selected <option>
elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1
if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text()
.
如果value=""
可能包含引号或其他会干扰选择器的特殊字符,请使用
If the value=""
may contains quotes or other special characters that would interfere with the selector, use .filter()
instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
这篇关于获得“最新"消息.从多个选择列表中选择的选项的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!