我正在使用PHP删除记录。我想使用JQuery UI对话框来确认操作,但我不知道如何将变量(我的RecordID)传递给重定向URL函数,或者允许URL访问window.location.href
。
$("#confirm" ).dialog({
resizable: false,
autoOpen: false,
modal: true,
buttons: {
'OK': function() {
window.location.href = 'url and myvar??';
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
}
});
$("#delete").click(function() {
$("#confirm").dialog( "open" ).html ( "Are U Sure?" );
return false;
});
HTML
<a href='index.php?recordid=$row[recordid]' id='delete'>DELETE</a>
有没有好办法呢?
答案 0 :(得分:74)
您可以尝试使用.data()方法为您存储数据。看看这个答案 Passing data to a jQuery UI Dialog
例如,为了传递变量,您可以在打开对话框之前使用数据函数存储它
$("#dialog_div")
.data('param_1', 'whateverdata')
.dialog("open");
然后你可以通过以下方式得到这个:
var my_data = $("#dialog_div").data('param_1')
答案 1 :(得分:7)
您想要在单击时更改对话框的配置(在这种情况下,“确定”按钮的行为)。为此你有很多解决方案,所有这些都是丑陋的(imo)。我建议动态生成一个对话框,并在使用它后将其销毁,如下所示:
$("#delete").click(function(ev) {
ev.preventDefault(); // preventDefault should suffice, no return false
var href = $(this).attr("href");
var dialog = $("<div>Are you sure?</div>");
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
window.location = href;
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
});
甚至更好,将确认对话框封装到一个函数中,以便您可以重复使用它,如下所示:
function confirmDialog(msg) {
var dialog = $("<div>"+msg+"</div>");
var def = $.Deferred();
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
def.resolve();
$( this ).dialog( "close" );
},
'Cancel': function() {
def.reject();
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
return def.promise();
}
然后像这样使用它
confirmDialog("are your sure?").done(function() {
window.location = $(this).attr("href");
}).fail(function() {
// cry a little
});
您可能必须在关闭对话框之前检查延迟对象是否已被拒绝或已解决,以确保在关闭时确认拒绝(而不仅仅是按下“取消”按钮)。这可以使用def.state()===“pending”条件来完成。
有关延迟jquery的更多信息:http://api.jquery.com/category/deferred-object/
答案 2 :(得分:0)
删除动作可能不应该使用GET来完成,但是如果你想这样做,我建议在jQuery中使用$ .data,这样每个链接都有一个data-record-id属性。然后单击其中一个链接,它会弹出对话框,确认后会将其添加到URL,然后重定向。 示例:强>
$(function(){
$(".deleteLink").click(function(){
var id = $(this).data("record-id");
var myHref = $(this).attr('href');
$("#confirmDialog").dialog({
buttons:{
"Yes": function()
{
window.location.href = myHref + id;
}
}
});
});
});
<a class="deleteLink" data-record-id="1">Delete</a>
...
<div id="confirmDialog">
<p>Are you sure?</p>
</div>
答案 3 :(得分:0)
HTML
<a data-title="Title" data-content="content" data-mydata="1" class="confirmation-dialog" href="#">Link</a>
JS
$('.confirmation-dialog').confirm({
buttons: {
Yes: function(){
console.log(this.$target.attr('data-mydata'));
No: function(){
}
}
});