2014-12-03 96 views
-1

嗨,大家好,我從網絡獲得了以下代碼並根據需要進行了修改,但未按預期工作。如何使用jQuery單擊取消按鈕時恢復下拉選擇選項?

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); 
     DummyFun(); 
    } 
}); 

function DummyFun() 
{ 
    alert(lastValue); 
    $(this).val(lastValue); 
} 

這裏是我從哪裏得到的代碼,它工作正常fiddle。我怎樣才能讓我的工作像小提琴一樣工作?

回答

1

在DummyFun函數中不能使用$(this)來引用select元素,因爲它超出了範圍。

function DummyFun() 
{ 
    alert(lastValue); 
    $("#changer").val(lastValue); 
} 
1

問題是函數DummyFun。 this不是指元素輸入不在範圍內。 this指的是調用該函數的內容。請使用以下內容:

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); 
     DummyFun(e.currentTarget); 
    } 
}); 

function DummyFun(target) 
{ 
    alert(lastValue); 
    $(target).val(lastValue); 
} 
相關問題