相关疑难解决方法(0)

jQuery如何撤消选择更改

我有一个选择框,我想在将其更改为特定选项之前添加确认.例:

<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)

有没有更简单/更好的方法来实现这一目标?

jquery

38
推荐指数
1
解决办法
5万
查看次数

标签 统计

jquery ×1