ove*_*ove 45 javascript jquery events select
如果某个条件适用,我想阻止更改选择框.这样做似乎不起作用:
$('#my_select').bind('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
我猜这是因为到目前为止所选的选项已经改变了.
这样做的其他方法是什么?
mat*_*ven 48
试试这个:
var my_condition = true;
var lastSel = $("#my_select option:selected");
$("#my_select").change(function(){
if(my_condition)
{
lastSel.prop("selected", true);
}
});
$("#my_select").click(function(){
lastSel = $("#my_select option:selected");
});
Run Code Online (Sandbox Code Playgroud)
小智 30
如果有人需要mattsven的答案的通用版本(就像我做的那样),这里是:
$('select').each(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
$('select').change(function() {
if(my_condition) {
$(this).data('lastSelected').attr('selected', true);
}
});
$('select').click(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
Run Code Online (Sandbox Code Playgroud)
小智 9
如果您只是想在my_condition为true时完全阻止与select的交互,那么您可以随时捕获mousedown事件并使事件阻止:
var my_condition = true;
$("#my_select").mousedown(function(e){
if(my_condition)
{
e.preventDefault();
alert("Because my_condition is true, you cannot make this change.");
}
});
Run Code Online (Sandbox Code Playgroud)
这将防止在my_condition为true时发生任何更改事件.