jQuery - 取消下拉列表的确认对话框上的更改事件

Vin*_*inu 27 javascript jquery

我有一个下拉列表,我有jQuery change函数.

我想根据确认对话框实现所选项目的更改.

如果确认为真,我可以继续进行选定的更改,否则我将现有项目保持为已选中并取消更改事件.

我如何用jQuery实现这个?

jquery函数

$(function () {
    $("#dropdown").change(function () {
        var success = confirm('Are you sure want to change the Dropdown ????');
        if (success == true) {
            alert('Changed');  
            // do something                  
        }
        else {
            alert('Not changed');
            // Cancel the change event and keep the selected element
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

记住change函数的一件事只有在选定的项目发生变化后才能点击所以更好地考虑实现它onchange- 但它在jquery中不可用.有没有办法实现这个?

Ben*_*enM 42

好吧,正如Vinu正确指出的那样,jQuery的change事件只有在select值实际发生变化时才会触发.你最好做这样的事情:

var prev_val;

$('#dropdown').focus(function() {
    prev_val = $(this).val();
}).change(function() {
     $(this).blur() // Firefox fix as suggested by AgDude
    var success = confirm('Are you sure you want to change the Dropdown?');
    if(success)
    {
        alert('changed');
        // Other changed code would be here...
    }  
    else
    {
        $(this).val(prev_val);
        alert('unchanged');
        return false; 
    }
});
Run Code Online (Sandbox Code Playgroud)


Swa*_*der 23

像我在这里做的一样?

http://jsfiddle.net/Swader/gbdMT/

只需在用户单击选择框时立即保存该值,并在onchange确认返回false时恢复为此值.

这是我小提琴的代码:

var lastValue;

$("#changer").bind("click", function(e) {
    lastValue = $(this).val();
}).bind("change", function(e) {
    changeConfirmation = confirm("Really?");
    if (changeConfirmation) {
        // Proceed as planned
    } else {
        $(this).val(lastValue);
    }
});
Run Code Online (Sandbox Code Playgroud)


Er.*_*.KT 5

使用以下代码,我已经测试了它和它的工作

var prev_val;
$('.dropdown').focus(function() {
    prev_val = $(this).val();
}).change(function(){
            $(this).unbind('focus');
            var conf = confirm('Are you sure want to change status ?');

            if(conf == true){
                //your code
            }
            else{
                $(this).val(prev_val);
                $(this).bind('focus');
                return false;
            }
});
Run Code Online (Sandbox Code Playgroud)