我有一个选择框,我想在将其更改为特定选项之前添加确认.例:
<select name="select">
<option value="foo" selected="selected">foo</option>
<option value="bar">bar</option>
</select>??????????????????Run Code Online (Sandbox Code Playgroud)
$('select').change(function() {
var selected = $(this).val();
if (selected == 'bar') {
if (!confirm('Are you sure?')) {
// set back to previously selected option
}
}
});Run Code Online (Sandbox Code Playgroud)
我正在考虑添加一个隐藏的输入字段,并在每次更改选择时更新其值.这样我就可以检索change函数中的前一个值.示例:
<input type="hidden" name="current" value="foo" />Run Code Online (Sandbox Code Playgroud)
$('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);
});Run Code Online (Sandbox Code Playgroud)
有没有更简单/更好的方法来实现这一目标?
lon*_*day 80
您可以使用以下$.data功能,而不是使用全局变量(evil!)或隐藏元素(滥用DOM):
$('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());
});
Run Code Online (Sandbox Code Playgroud)