jQuery 绑定事件到选定的选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11279898/
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
Binding event to chosen select
提问by Boss Nass
I have this code for a select box which is being displayed by the Chosen jQuery plugin. What I am trying to achieve is to get the value from the current item that has been selected:
我有一个选择框的代码,它由 Chosen jQuery 插件显示。我想要实现的是从已选择的当前项目中获取值:
<div>
<select id="schedule_event" name="schedule[event]" style="display: none; " class="chzn-done"><option value="Game" selected="selected">Game</option>
<option value="Event">Event</option>
<option value="Training">Training</option>
</select>
<div id="schedule_event_chzn" class="chzn-container chzn-container-single chzn-container-active" style="width: 854px; ">
<a href="javascript:void(0)" class="chzn-single chzn-single-with-drop" tabindex="-1">
<span>Game</span>
<div></div>
</a>
<div class="chzn-drop" style="width: 849px; top: 27px; left: 0px; ">
<div class="chzn-search">
<input type="text" autocomplete="off" style="width: 814px; " tabindex="0">
</div>
<ul class="chzn-results">
<li id="schedule_event_chzn_o_0" class="active-result result-selected highlighted" style="">Game</li>
<li id="schedule_event_chzn_o_1" class="active-result" style="">Event</li>
<li id="schedule_event_chzn_o_2" class="active-result" style="">Training</li>
</ul>
</div>
</div>
</div>
The JavaScript I'm using at the moment to find the current value is:
我目前用来查找当前值的 JavaScript 是:
$("#schedule_event").chosen().change( function() {
alert(+ $(this).text());
$('#' + $(this).val()).show();
});
However, I keep getting a 'NaN', ie no value.
但是,我不断收到“NaN”,即没有价值。
回答by Tats_innit
Code:
代码:
$(".chzn-select").chosen().change(function() {
alert(+$(this).val());
//$('#' + $(this).val()).show();
});
Demo:
演示:
Working demo: http://jsfiddle.net/MM7wh/
工作演示:http: //jsfiddle.net/MM7wh/
Edit (6th July 2015)
编辑(2015 年 7 月 6 日)
cdns are changed now.
cdns现在改变了。
Working demo: http://jsfiddle.net/uk82dm5L/
工作演示:http: //jsfiddle.net/uk82dm5L/
Please use $(this).val()
instead of .text()
.
请使用$(this).val()
代替.text()
。
回答by user7051905
Personally I prefer use this:
我个人更喜欢使用这个:
$(document).on('change', '#mychosen', function(evt, params) {
if (params.selected != undefined)
{
console.log('selected: ' + params.selected);
}
if (params.deselected != undefined)
{
console.log('deselected: ' + params.deselected);
}
});