作者:501917112_0de975_837 | 来源:互联网 | 2023-01-15 17:11
我有一些内容可以使用该Id上的ajax进行更新,例如,假设我有一个完整的主页,并且body
我有这个代码:
和index.html
的第1页包含像这样的代码:
.....
和index.html
的第二页中包含一些像这样的代码:
.....
并script.js
包含一些像这样的代码:
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
});
我想要做的是当按下按钮调用从Page1获取index.html的Ajax 并将其放入id内容时,运行script.js
此脚本仅在id page1存在时执行,我从这个答案中找到了这个技巧例如,通过使用带有jQuery的if,if($('#page1').length ){my sj code}
Javascript代码仅在该id存在时运行,但不幸的是,当我单击按钮以获得具有另一个id page2代码保持运行的Page2时,有没有办法在此时停止此js代码div更新???
1> MennyMez..:
该功能没有停止,因为除非您使用clearInterval()
函数清除它,否则间隔不会停止触发.
只需将所有JS代码放在一个文件中,如下所示:
$(document).ready(function() {
var the_interval = setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
function stopTheInterval(){
clearInterval(the_interval);
}
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
stopTheInterval(); // we stop the first interval
}
});
}});
我在这里做的是在变量中保存区间数,并创建一个新函数来清除它.接下来,我所做的只是将我的新函数放在你的update2()函数中,所以一旦我得到数据,我就清除间隔并停止重复函数.