开发者

Passing a variable to setIntervall function

开发者 https://www.devze.com 2023-03-09 17:21 出处:网络
i am calling a jQuery plugin every 5 seconds with the following code var now = new Date(); setInterval(\'$(\"#id\").myp开发者_如何学Golugin(now)\', 1000);

i am calling a jQuery plugin every 5 seconds with the following code

    var now = new Date();

    setInterval('$("#id").myp开发者_如何学Golugin(now)', 1000);

The Plugin looks like this so far:

    (function( $ ){
    $.fn.myplugin = function(now) {
        return this.each(function() {
            alert(now.getTime());
        });
    }
   })( jQuery );

However I get the error:

Uncaught ReferenceError: now is not defined

plugins.js:30 Uncaught TypeError: Cannot call method 'getTime' of undefined

So it looks as if the now time object doenst get passed to the plugin function and is not even defined in the setInterval method. I could probably call var now = new Date(); every time in the plugin function ... but I want to know, why it doenst work like that and how to make it work ;). thx alot.


Use a function like this:

var now = new Date();

setInterval(function() {
    $("#id").myplugin(now);
}, 1000);

This way, the so-called scope of now is set to the function in which you call setInterval. Otherwise, it is just the global object (window) you're referring to, which doesn't have a now.

Secondly, passing a string works like eval(), which is unsafe and slow: Why is eval unsafe in javascript?.


Use this instead:

setInterval(function(){$("#id").myplugin(now)}, 1000);
0

精彩评论

暂无评论...
验证码 换一张
取 消