0

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?

4

2 回答 2

6

setInterval返回一个整数,它是计时器的 id。因此,您所要做的就是存储它:

var interval = setInterval(function(){
// ...
    clearInterval(interval);
于 2012-05-21T18:39:50.207 回答
3

为您的区间保留一个变量:

document.body.addEventListener("keypress", f1, false);

function f1(e){
    var span = document.createElement("span");
    var myInterval = setInterval(function(){
        ...
            clearInterval(myInterval);
            document.body.removeChild(span);
}
于 2012-05-21T18:38:56.690 回答