由于您是编码新手,我建议您使用 jQuery 团队的 jQueryUI 库——其中包括 .dialog() 功能(他们称之为“小部件”)。以下是它的工作原理:
(1) 在您的<head></head> 标签中包含jQuery 和 jQueryUI 库。请注意,您还必须为 jQueryUI 包含适当的 CSS 主题库(否则对话框将不可见):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/flick/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
(2) 在您的 HTML 中创建一个空 div,并将其初始化为一个对话框:
HTML:
<div id="myDlg"></div>
jquery:
$('#myDlg').dialog({
autoOpen:false,
modal:true,
width: 500,
height: 'auto'
});
(3) 然后,当您准备好显示对话框时,在打开对话框之前将新数据插入myDlg div:
$('#myDlg').html('<div>This will display in the dialog</div>');
$('#myDlg').dialog('open');
上面允许你改变对话框的内容,每次都使用重新相同的对话框DIV。
工作示例如下所示:
jsFiddle Demo
HTML:
<div id="myDlg"></div>
<div id="questiona" class="allques">
<div class="question">What is 2 + 2?</div>
<div class="answer">4</div>
</div>
<div id="questionb" class="allques">
<div class="question">What is the 12th Imam?</div>
<div class="answer">The totally wacky reason why Iran wants a nuclear bomb.</div>
</div>
jQuery:
var que,ans;
$('#myDlg').dialog({
autoOpen:false,
modal:true,
width: 500,
height: 'auto',
buttons: {
"See Answer": function(){
$('#myDlg').html(ans);
$('.ui-dialog-buttonset').next('button').hide();
},
"Close": function(){
$('#myDlg').html('').dialog('close');
}
}
});
$('.allques').click(function(){
que = $(this).find('.question').html();
ans = $(this).find('.answer').html();
$('#myDlg').html(que).dialog('open');
});
资源:
How to use Plugins for PopUp
http://jqueryui.com/dialog/
http://blog.nemikor.com/2009/04/08/basic-usage-of-the-jquery-ui-dialog/
jQuery UI Dialog Box - does not open after being closed
Dynamically changing jQueryUI dialog buttons
jQuery UI dialog - problem with event on close