定制“确认” JavaScript中的对话框? [英] Custom "confirm" dialog in JavaScript?
问题描述
在网站的许多部分,我的代码如下所示:
var warning ='你确定要这样做吗?
if(confirm(warning)){
// do something
}
else {
// do something else
}
这是可以的,但让确认对话框匹配页面其余部分的风格是很好的。 p>
然而,由于它不是一个真正的模态对话框,我认为我需要这样写:(我在本例中使用jQuery-UI)
< div id ='modal_dialog'>
< div class ='title'>
< / div>
< input type ='button'value ='yes'id ='btnYes'/>
< input type ='button'value ='no'id ='btnNo'/>
< / div>
< script>
函数DoSomethingDangerous(){
var warning ='你确定要这样做吗?
$('。title')。html(warning);
var dialog = $('#modal_dialog')。dialog();
function Yes(){
dialog.dialog('close');
//做某事
}
function No(){
dialog.dialog('close');
//做其他事情
}
$('#btnYes')。点击(是);
$('#btnNo')。点击(否);
}
是这是一个很好的方式来完成我想要的,还是有更好的方法?
你可能想考虑抽象出来转换成这样的函数:
函数对话框(message,yesCallback,noCallback){
$(' )。html的(消息);
var dialog = $('#modal_dialog')。dialog();
$('#btnYes')。click(function(){
dialog.dialog('close');
yesCallback();
});
$('#btnNo')。click(function(){
dialog.dialog('close');
noCallback();
});
}
然后,您可以使用它:
对话框('你确定要这样做吗?'
function(){
// do something
},
function(){
// do something else
}
);
I've been working on an ASP.net project that uses custom 'modal dialogs'. I use scare quotes here because I understand that the 'modal dialog' is simply a div in my html document that is set to appear "on top" of the rest of the document and is not a modal dialog in the true sense of the word.
In many parts of the web site, I have code that looks like this:
var warning = 'Are you sure you want to do this?';
if (confirm(warning)) {
// Do something
}
else {
// Do something else
}
This is okay, but it would be nice to make the confirm dialog match the style of the rest of the page.
However, since it is not a true modal dialog, I think that I need to write something like this: (I use jQuery-UI in this example)
<div id='modal_dialog'>
<div class='title'>
</div>
<input type='button' value='yes' id='btnYes' />
<input type='button' value='no' id='btnNo' />
</div>
<script>
function DoSomethingDangerous() {
var warning = 'Are you sure you want to do this?';
$('.title').html(warning);
var dialog = $('#modal_dialog').dialog();
function Yes() {
dialog.dialog('close');
// Do something
}
function No() {
dialog.dialog('close');
// Do something else
}
$('#btnYes').click(Yes);
$('#btnNo').click(No);
}
Is this a good way to accomplish what I want, or is there a better way?
You might want to consider abstracting it out into a function like this:
function dialog(message, yesCallback, noCallback) {
$('.title').html(message);
var dialog = $('#modal_dialog').dialog();
$('#btnYes').click(function() {
dialog.dialog('close');
yesCallback();
});
$('#btnNo').click(function() {
dialog.dialog('close');
noCallback();
});
}
You can then use it like this:
dialog('Are you sure you want to do this?',
function() {
// Do something
},
function() {
// Do something else
}
);
这篇关于定制“确认” JavaScript中的对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!