使用 jquery 取消确认后如何防止更改 select 选项?

How to prevent changing of select option after cancelling confirm using jquery?

所以我有一个 select 选项字段,我更改了 select 字段的选项,将显示一条确认消息。我的问题是如何防止在取消确认消息后更改 select 选项字段的值。

$('.changeScoreFem').on('change', function(){
    if (confirm('Are you sure to change this score?')) {
        //continue to change  the value
    } else {
        //else do not change the selecoption field value
    }
});

您需要将所选选项存储在变量中,如果确认取消,请重新选择它。

var selected = $(".changeScoreFem option:selected");
$(".changeScoreFem").on("change", function(e){
    if (confirm("Are you sure to change this score?"))
        selected = $(this).find("option:selected");
    else
        selected.prop("selected", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="changeScoreFem">
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select>

您可以通过存储 select 的当前值来执行此操作,然后根据需要撤消它。

以下使用自定义事件来存储数据,如果您从服务器select传递 selected 项目

,该自定义事件也会在页面加载时触发
var $sel = $('.changeScoreFem').on('change', function(){
    if (confirm('Are you sure to change this score?')) {
        // store new value        
        $sel.trigger('update');
    } else {
         // reset
         $sel.val( $sel.data('currVal') );        
    }
}).on('update', function(){
    $(this).data('currVal', $(this).val());
}).trigger('update');

DEMO