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