JavaScript范围:定时器引用任意新对象(JavaScript Scope: timer referencing arbitrary new object)

编程入门 行业动态 更新时间:2024-10-28 16:16:40
JavaScript范围:定时器引用任意新对象(JavaScript Scope: timer referencing arbitrary new object)

这是我基本上要做的代码:

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);

更多推荐

本文发布于:2023-08-01 13:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1360130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定时器   对象   Scope   JavaScript   arbitrary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!