我有一个可以正常工作的 jQuery 对话框的现有链接。但是当我尝试插入一个新的对话框链接时,使用 .on() 来选择一个现有的 div,该链接不会生成对话框,而是简单地链接到页面。
有人可以帮助说明应该如何做吗?
这是一个代码示例:
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("<p><a href='a.html' class='mdialog' name='mine' title='mine' >new link</a></p>").insertAfter("button");
});
// this works to produce a dialog for an existing link
$('.mdialog').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
resizable: false,
modal: true,
autoOpen: false,
closeOnEscape: true,
position: 'center',
title: $link.attr('title'),
buttons: {
"Close": function() {
$( this ).dialog( "close" );
}
}
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
});
$("#mydiv").on("click","a",function(){
alert("I'm clicked"); // link click is being handled
// same code as above does not produce a dialog
$('.mdialog').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
resizable: false,
modal: true,
autoOpen: false,
closeOnEscape: true,
position: 'center',
title: $link.attr('title'),
buttons: {
"Close": function() {
$( this ).dialog( "close" );
}
}
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
});
});
});
</script>
</head>
<body>
<div id="mydiv">
<p><a href='a.html' class='mdialog' name='mine' title='mine' >existing link</a></p>
<button>Insert a new paragraph with anchor element after this button</button>
</div>
</body>
</html>
a.html 只是一个非常简单的消息:
<p>this should be a dialog message!</p>
下面的EDIT似乎确实允许新注入的对话框正常工作。现在是#1。正如 Jamie 建议的那样,消除了 .each 循环和#2。删除 $link.click() 处理程序以打开对话框和#3。添加一个 event.preventDefault() 以防止页面实际被链接而不是对话框:
$("#mydiv").on("click","a",function(event){
//alert("I'm clicked"); // link click is being handled
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
resizable: false,
modal: true,
autoOpen: false,
closeOnEscape: true,
position: 'center',
title: $link.attr('title'),
buttons: {
"Close": function() {
$( this ).dialog( "close" );
}
}
});
//$link.click(function() {
$dialog.dialog('open');
// return false;
//});
event.preventDefault();
});