我有一个选择框,我想在将其更改为特定选项之前添加确认。例子:
<select name="select">
<option value="foo" selected="selected">foo</option>
<option value="bar">bar</option>
</select>
$('select').change(function() {
var selected = $(this).val();
if (selected == 'bar') {
if (!confirm('Are you sure?')) {
// set back to previously selected option
}
}
});
我正在考虑添加一个隐藏的输入字段,并在每次选择更改时更新其值。这样我就可以检索以前的值change
功能。Example http://jsfiddle.net/eUM4D/:
<input type="hidden" name="current" value="foo" />
$('select').change(function() {
var selected = $(this).val();
var current = $('input[name=current]').val();
if (selected == 'bar') {
if (!confirm('Are you sure?')) {
$(this).val(current);
return false;
}
}
$('input[name=current]').val(selected);
});
有没有更简单/更好的方法来实现这一点?
您可以使用以下方法,而不是使用全局变量(邪恶!)或隐藏元素(滥用 DOM)$.data http://api.jquery.com/jQuery.data/特征:
$('select').change(function() {
var selected = $(this).val();
if (selected == 'bar') {
if (!confirm('Are you sure?')) {
$(this).val($.data(this, 'current'));
return false;
}
}
$.data(this, 'current', $(this).val());
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)