gpt4 book ai didi

javascript - 函数不适用于 setTimeout

转载 作者:行者123 更新时间:2023-11-28 05:19:45 25 4
gpt4 key购买 nike

因此页面加载,但是页面的一部分是从服务器获取的,稍后加载,所以我设置了一个 setTimeout 函数,但是在执行此操作之后出现错误

Uncaught ReferenceError :检查未定义

我也将检查功能移到 setTimeout 之外,但还是不行

当在开发者控制台的所有内容中粘贴时没有超时功能,检查功能工作正常。

setTimeout(function() {


var getclass = document.getElementsByClassName('title');
var containerlength = getclass.length;

for (var i = 0; i < containerlength; i++) {
var container = getclass[i];
var jobid = getclass[i].children[0].innerHTML.trim().substring(0, 5);
var fragment = document.createElement('div');
var chk = "";
if (localStorage.getItem(jobid) == 1) {
chk = "checked";
getclass[i].style.textDecoration = 'line-through';
}
fragment.innerHTML = '<input onclick="check(this)" class="jobs" value="' + jobid + '" name="' + jobid + '" type="checkbox"' + chk + '></input>';
container.appendChild(fragment);

}

function check(ele) {
// alert(ele.name);
var name = ele.name;
var papa = ele.parentNode.parentNode;
if (localStorage.getItem(name) == 1) {
localStorage.setItem(name, 0);
papa.style.textDecoration = 'none';
} else {
localStorage.setItem(name, 1);
papa.style.textDecoration = 'line-through';
}
}


}, 5000);

最佳答案

这可能是因为您在 setTimeout 回调的范围内定义了检查函数。尝试将检查功能移出范围,如下所示:

function check(ele)
{
// alert(ele.name);
var name = ele.name;
var papa = ele.parentNode.parentNode;
if(localStorage.getItem(name) == 1)
{
localStorage.setItem(name, 0);
papa.style.textDecoration = 'none';
}
else
{
localStorage.setItem(name, 1);
papa.style.textDecoration = 'line-through';
}
}


setTimeout(function(){

var getclass = document.getElementsByClassName('title');
var containerlength = getclass.length;

for(var i=0; i<containerlength; i++)
{
var container = getclass[i];
var jobid = getclass[i].children[0].innerHTML.trim().substring(0, 5);
var fragment = document.createElement('div');
var chk = "";
if(localStorage.getItem(jobid) == 1)
{
chk = "checked";
getclass[i].style.textDecoration = 'line-through';
}
fragment.innerHTML = '<input onclick="check(this)" class="jobs" value="' + jobid + '" name="' + jobid + '" type="checkbox"' + chk + '></input>';
container.appendChild(fragment);

}
}, 5000);

关于javascript - 函数不适用于 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40205254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com