[英]jquery ui dialog box as confirm
我正在嘗試使用jquery對話框復制javascript的“確認”框。 這是我的代碼,
function customConfirm(customMessage) {
$("#popUp").html(customMessage);
$("#popUp").dialog({
resizable: false,
height: 240,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
alert(true);
return true;
},
Cancel: function () {
$(this).dialog("close");
alert(false);
return false;
}
}
});
}
但是當我試圖提醒這個方法時,它會顯示“未定義”。 它不是在等待彈出窗口顯示。 如何使這個customConfirm功能等待用戶輸入(確定/取消)? 我需要的是,customConfirm()方法將根據用戶輸入返回true或false。
你需要做的是使用jQuery.deferred / promise。
http://api.jquery.com/deferred.promise/
在此示例中,asyncEvent
1)創建一個jquery延遲對象
2)有解決/拒絕的邏輯,你的確定/取消
3)返回一個deferred.promise()對象,然后可以與$ .when一起使用,以確定是否已解析或拒絕延遲對象(ok / cancel)。
你要做的是
1)創建一個jquery延遲對象
2)啟動對話框,使用ok / cancel設置deferred.resolve / reject
3)返回一個deferred.promise()對象,
4)使用延遲的promise對象與$ .when http://api.jquery.com/jQuery.when/
function customConfirm(customMessage) {
var dfd = new jQuery.Deferred();
$("#popUp").html(customMessage);
$("#popUp").dialog({
resizable: false,
height: 240,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
alert(true);
dfd.resolve();
},
Cancel: function () {
$(this).dialog("close");
alert(false);
dfd.reject();
}
}
});
return dfd.promise();
}
$.when( customConfirm('hey') ).then(
function() {
alert( "things are going well" );
},
function( ) {
alert( "you fail this time" );
});
您也可以使用resolve並確定$ .when中的確認是真還是假,
function customConfirm(customMessage) {
var dfd = new jQuery.Deferred();
$("#popUp").html(customMessage);
$("#popUp").dialog({
resizable: false,
height: 240,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
alert(true);
dfd.resolve(true);
},
Cancel: function () {
$(this).dialog("close");
alert(false);
dfd.resolve(false);
}
}
});
return dfd.promise();
}
$.when( customConfirm('hey') ).then(
function(confirm) {
if(confirm){alert( "things are going well" );}
else{alert( "you fail this time" );}
});
希望有所幫助。
這就是我使用zepto進行模塊延遲和回調,就像一個魅力。 對於jquery應該是類似的,或者你可以將deferred和callbacks模塊導入你的html
function customConfirm(customMessage) {
var d = new $.Deferred();
$("#popUp").html(customMessage);
$("#popUp").dialog({
resizable: false,
height: 300,
modal: true,
buttons: {
"Yes": function () {
$(this).dialog("close");
d.resolve()
},
"No": function () {
$(this).dialog("close");
d.reject();
}
}
});
return d.promise();
}
customConfirm("Do you Want to delete the File?")
.then(function(){
console.log("You Clicked Yes")
})
.fail(function(){
console.log("You Clicked No")
});
您應該在文檔就緒功能上加載對話框。 在customConfirm
函數上打開調用對話框,
function customConfirm(customMessage) {
$("#popUp").html(customMessage);
$("#popUp").dialog("open");
}
$(document).ready(function (){
$("#popUp").dialog({
resizable: false,
autoOpen: false,
height: 240,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
alert(true);
return true;
},
Cancel: function () {
$(this).dialog("close");
alert(false);
return false;
}
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.