0

当从对话框中选择特定选项时,我正在使用下面显示的代码创建一个确认框<select>。I am able to get the confirm dialog just fine when the "bar" option is selected. 但是,如果我取消它,所选选项将变为空白。如果我首先选择另一个选项,然后选择“栏”并取消,它会返回到先前选择的选项(这是所需的行为)。为什么第一次取消失败而后续取消没有?

<html>
    <head>
        <title>Test of jQuery confirm select</title>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">
            $(function(){
                $('#example').change(function() {
                    var selected = $(this).val();

                    if (selected == 'bar') {
                        if (!confirm('Are you sure?')) {
                            $(this).val($.data(this, 'current')); // added parenthesis (edit)
                            return false;
                        }     
                    }
                    $.data(this, 'current', $(this).val());
                });
            });
        </script>
    </head>
        <select id="example">
            <option value="none" selected="selected">--Select an Option--</option>
            <option value="foo">foo</option>
            <option value="bar">bar</option>
            <option value="que">que</option>
        </select>
    <body>
    </body>
</html>

jsFiddle 演示

为了清楚起见,如果我从任何其他选项转到“栏”,这不会发生。但是如果“bar”是我选择的第一个选项,它总是会发生。

4

1 回答 1

1

这是因为current第一次运行这个函数时没有设置。

if在您的第一条语句之前插入以下内容:

if($.data(this, 'current') == null) $.data(this, 'current', 'none');      

jsFiddle

于 2013-08-16T20:27:32.357 回答