jQuery如何撤消选择更改

Ale*_*lec 38 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)

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

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)

  • 要用初始值初始化'current',我切换到$(this).data(...)而不是$ .data(this,...)然后添加到我的脚本:if($('select').length> 0){$('select').data('current',$('select').val()); } (7认同)
  • 很好,不知道那一个.非常有用,效果很好!谢谢. (3认同)
  • 干得好.是否需要额外的一行来用初始值初始化'current',并且2010年没有$(this).data()? (3认同)
  • 或者使用`$(this).data('key',val)`这对我来说似乎更清晰.哎呀,@ TolandHon已经注意到了.向他投票! (2认同)