这是我基本上要做的代码:
document.body.addEventListener("keypress", f1, false); function f1(e){ var span = document.createElement("span"); window.setInterval(function(){ ... window.clearInterval(this); document.body.removeChild(span); }所以简而言之,我正在尝试创建一个新的DOM元素,然后为它附加一个能够引用该特定对象的计时器。 问题是,我不知道如何处理上下文,所以this只是引用window ,当我尝试引用span时,JavaScript会抛出错误(我还没想到它会工作)。 如何设置我在该函数中创建的DOM元素的区间上下文?
Here is the code for what I am basically trying to do:
document.body.addEventListener("keypress", f1, false); function f1(e){ var span = document.createElement("span"); window.setInterval(function(){ ... window.clearInterval(this); document.body.removeChild(span); }So in short, I'm trying to make a new DOM element, and then attach a timer to it that will be able to reference that particular object. The problem is, I don't know how to do the context, so this just references window, and JavaScript throws an error when I try to reference span (which I wasn't expecting to work anyway). How can I set the context of the interval to the DOM element I created in that function?
最满意答案
setInterval返回一个整数,它是计时器的id。 所以,你所要做的就是存储它:
var interval = setInterval(function(){ // ... clearInterval(interval);setInterval returns an integer which is the id of the timer. So, all you have to do is to store it:
var interval = setInterval(function(){ // ... clearInterval(interval);更多推荐
发布评论