我的select
有问题。
我希望already selected
选项也触发.change()
函数。
目前,只有在选择了其他选项时才会触发。
如何在没有太多Soucrecode的情况下提出这种可能性。也许已经有可能我不知道。
修改
我或许应该提一下它应该适用于移动浏览器!
答案 0 :(得分:2)
编辑: IE无法妥善处理! :(
要支持IE,您可以使用:
$(document).ready(function () {
var con = $('#console');
$('select').change(function () {
/* change also on already selected option */
con.append('- ' + $(this).val() + '<br/>');
//$(this).blur();
}).change().bind('mousedown', function () {
this.selectedIndex = -1;
this.selectedIndex = $(this).find('option:selected').index();
});
});
看看是否符合您的需求:
$(document).ready(function () {
var con = $('#console');
$('select').change(function () {
/* change also on already selected option */
con.append('- ' + $(this).val() + '<br/>');
}).change().bind('mousedown', function () {
//on mousedown, clone SELECT element to display current selected value
// this would be empty value otherwise when setting current selected index
// NOTE: seems to be still not as good on IE...
// FF would need to redefine some margin/padding
if (!$(this).data('cloned')) $(this).data('cloned', $(this).clone().css({
position: 'absolute',
pointerEvents: 'none',
top: this.offsetTop,
left: this.offsetLeft,
margin: 0
}).appendTo('body'));
// here set selectedIndex of SELECT element to not defined index
// this would let on change event to be fired in all cases
this.selectedIndex = -1;
}).blur(function(){
// on blur, remove cloned SELECT element and reset specific data object
if ($(this).data('cloned')) {
this.value = $(this).data('cloned').val();
$(this).data('cloned').remove();
$(this).data('cloned', null);
}
});
});
答案 1 :(得分:0)
function onSelectChange(){
alert('changed');
};
var select2 = $("#select").select2().data('select2');
select2.onSelect = (function(fn) {
return function(data, options) {
var target;
if (options != null) {
target = $(options.target);
}
if (target) {
onSelectChange();
return fn.apply(this, arguments);
}
}
})(select2.onSelect);
<强> DEMO 强>
在HTML中:添加id
以选择
<select id="select">
<option selected>Selected</option>
<option>Not selected</option>
</select>
<div id="console"></div>