0
我有一个现有的链接到一个jQuery对话框,它的工作原理应该如此。但是,当我尝试插入新的对话链接时,使用.on()选择一个现有的div,链接不会生成对话框,而只是链接到页面。如何使用jQuery .on()来处理新插入的对话框链接的点击事件?
有人可以帮助显示这应该怎么做?
下面是一个代码示例:
<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>
的编辑下面似乎确实使新注入的对话框工作正常。现在它#1。正如杰米建议的那样,消除了每个循环。删除$ 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();
});
是的,谢谢。它虽然没有帮助对话。任何想法为什么对话框代码不起作用? – aaron 2013-03-19 14:55:21
.on函数是否应该传递.each函数需要的东西? – aaron 2013-03-19 15:00:16
查看更新的答案 – 2013-03-19 15:08:34