获取“最新”信息从多个选择列表中选择的选项文本
我有一个 HTML 选择列表,它可以有多个选择:
<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 来做到这一点:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
看起来很简单,但是如果选择列表已经有一些选定的选项 - 它也会返回它们的文本。例如,如果我已经选择了“第二”选项,那么在选择“第四”选项后,警报会给我带来这个 - “SecondFourth”。那么,是否有任何简短、简单的方法可以使用 jQuery 来仅获取“当前”所选选项的文本,或者我是否必须使用字符串并过滤新文本?
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>
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());
});
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行类似的操作,保留旧值数组并检查其中不存在哪个新值数组,如下所示:
在这里尝试一下,当你调用
.val()
时 在如果
value=""
可能包含引号或其他会干扰选择器的特殊字符,请使用.filter()
相反,如下所示:You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
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()
.If the
value=""
may contains quotes or other special characters that would interfere with the selector, use.filter()
instead, like this:在选项上设置 onClick 而不是选择:
Set a onClick on the option instead of the select:
或者让我们再玩点
干杯吧。
or let's play some more
Cheers.