ajax加载的内容中的函数也在删除后运行

时间:2012-05-22 17:41:38

标签: javascript jquery function

我的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><script src="js/jquery.js"></script>
<script>$(function(){
$("button:first").click(function(){
$("#aja").load("ajax.html");});
$("button:last").click(function(){
$("#aja").remove();});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<button>Load page</button><button id="rem">Remove ajax content</button>
<div id="aja"></div>
</body>
</html>

和ajax.html代码

<body>
<script>$(function(){
cool();});
function cool(){
$("button:last").after("Hello");
setTimeout("cool()",10000);}
</script>
</body>

现在,当我加载ajax.html时,它的cool()函数运行并继续向最后一个按钮添加hello。问题是当我用第二个按钮删除ajax加载的内容时,被删除的cool()函数继续运行。但我希望在删除ajax内容后停止使用cool函数

2 个答案:

答案 0 :(得分:0)

检查#aja块的存在可能有所帮助:

function cool() {
    if ($("#aja").length == 0) return;

    $("button:last").after("Hello");
    setTimeout("cool()", 10000);
}

答案 1 :(得分:0)