我有一个页面index.html
:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Lufia</title>
<script src="js/jquery.js" language="javascript"></script>
<script language="javascript">
$(document).ready(function() {
$("button").click(function() {
$('#mydiv').html( 'Loading... ').load('welcome.html');
$(this).hide();
});
});
</script>
</head>
<body>
<button>ajax</button><div id="mydiv"></div>
</body>
</html>
在此代码中,当在 midiv
中单击按钮时,加载 welcome.html
并且按钮被隐藏。
welcome.html
如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Lufia</title>
</head>
<body>
<button>New Button</button>
</body>
</html>
这个新按钮的 onClick
不起作用。为什么?
最佳答案
此处的简单解决方案 - 您需要使用 jQuery .live()
函数为新按钮添加事件处理程序。
$("#newButton").live('click',function(){
// Do stuff here
});
当您最初创建 .click()
处理程序时,第二个 button
尚未在 DOM 中,因此 jQuery 无法向其附加事件处理程序。 .live()
函数适用于 DOM 中已有的任何元素以及将来添加的任何元素(例如,来自 ajax 调用)。
您可能想要为您的新按钮(来自 ajax 调用)提供一个新的不同 ID,因为选择器 $("button")
将捕获您的两个按钮(即使其中一个按钮是隐藏的) .
注意!
自 jQuery 1.7 版起,live()
方法 has been deprecated! 。从版本 1.9 开始,此函数将被完全删除...处理这些动态添加元素的事件处理程序的正确方法现在是使用 on()
function.
关于jQuery 函数不适用于 AJAX 加载的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161938/