简体   繁体   中英

Setinterval won't work with text

hello I'm Coding a plug in for j Query but the problem i have to use the function $.now() anyway when i use it with alert() it works perfectly, but when i put it in a code it doesn't show anything and the text() works in plug-in also but the only problem is when i use the function set interval now thing shows up i have tried this code:

setInterval(function(){

this.text($.now());

},1000); 

it doesn't work but when i use alert it works so what i have to do?

You lose the context when inside the setinterval call back function. You can do this way.

//.. some event

var $this = $(this);

setInterval(function(){
   $this.text($.now());
},1000); 

//.. code follows

Or with $.proxy you can set the context.

setInterval($.proxy(function(){
   $(this).text($.now());
},this),1000); 

Or with Ecmascript 5 Function.prototype.bind ( Support for IE8 and below only through the shim mentioned in the document )

setInterval((function(){
   $(this).text($.now());
}).bind(this),1000); 

Here is a demo with all the three options

What does this refer to? Suggest you put the actual selector instead of this. Inside a function, the value of this can vary

var obj = $(".text");
setInterval(function(){
    obj.text($.now());
},1000); 

obj acts as a closure here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM