Javascript jQuery,在已选择的选项上也触发更改
我的选择有问题。 我希望已经选择的选项也触发.change函数。 当前,它仅在选择其他选项时触发。 如果没有太多的灵魂密码,我怎么能把这种可能性放在心上呢。也许已经有一种可能性我不知道 编辑: 我也许应该提到,它应该在移动浏览器上工作 在HTML中:添加要选择的idJavascript jQuery,在已选择的选项上也触发更改,javascript,jquery,Javascript,Jquery,我的选择有问题。 我希望已经选择的选项也触发.change函数。 当前,它仅在选择其他选项时触发。 如果没有太多的灵魂密码,我怎么能把这种可能性放在心上呢。也许已经有一种可能性我不知道 编辑: 我也许应该提到,它应该在移动浏览器上工作 在HTML中:添加要选择的id <select id="select"> <option selected>Selected</option> <option>Not selected</opt
<select id="select">
<option selected>Selected</option>
<option>Not selected</option>
</select>
<div id="console"></div>
编辑:IE处理得不好
要支持IE,您可以使用:
看看这是否符合你的需要:
您可以显示您的代码吗?以查看您尝试了什么。因为事件名称告诉您仅在值更改时触发更改…问:为什么您需要它在选择已选项目时重新触发?从用户界面的角度来看,你不会期望事件发生,因为没有任何变化。谢谢@Mr.TK我已经知道了…@TrueBlueAussie我需要它作为当前选项的刷新,它根本不起作用…它的触发器很快就会触发,在进行选择之前请检查演示url,您会发现,它的工作模式是在单击“选择”和“选项”时触发的@TrueBlueAussie当用户更改或不更改选项时,OP希望触发事件。因此,根据我的说法,这是最重要的。它在演示中工作。你能解释一下你在哪里定义.select2函数吗?很有趣。。。您能解释一下它是如何工作的吗?@TrueBlueAussie将此设置为.selectedIndex=-1,以在选定的任何选项上触发onchange事件。将克隆元素用于UI,否则选择反射值将为空。这需要更多的测试,看看这是否符合OP的需要。我不确定这是否能处理所有预期的案件,我认为这符合我的需要。如果你能在你的答案中解释你的代码,我认为你的答案是正确的。我必须承认,这很聪明!不幸的是,IE中的行为如此丑陋。点击反应和显示几乎无法使用。也许对IE进行一些调整以使其完美?
<select id="select">
<option selected>Selected</option>
<option>Not selected</option>
</select>
<div id="console"></div>
$(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);
}
});
});