开发者

writing javascripts function using jquery

Some template written using jquery is as follows . it is not working . Any suggestions to use jquery efficiently .

<html>  
<head>  
<script type="text/javascript" src="/jquerycall/"></script>  
<script type="text/javascript">  
    $(document).ready(function()  
    {  
        self.setInterval("clock()",1000);  
        $("button").click(function()  
        {  
            clock;  
        });  
        function clock()  
        {  
            clock();  
            time=new Date();  
            var s = "<p>" + time + "</p>";  
            $(s).appendTo("div");  
        }
    });  
</script>  
</head>  
<body>  
<form method="post">  
<button type="button">Click Me</button>  
<div id="someid">&l开发者_如何学Got;/div>  
</form>  
</body>  
</html>


function clock()   
{   
   //clock(); /* Remove this recursive call or you'll just get an infinite loop */
   var current = new Date(); /* Make sure to use var on variables */
   var s = "<p>" + current + "</p>";
   $('#someId').html(s); /* Assuming you want to set 'someId' to 's', not try and append all things that match s to every div */
} 

var clockStarted = false;
$("button").click(function()   
{   
   if (!clockStarted) /* You only need to set the clock to start once */
      setInterval(clock, 1000);  /* You only want the interval to start after you've clicked the button and you don't need 'self'. */
   clockStarted = true;

   //clock(); /* Said 'clock;' before */   
});  

To summarise:

  1. When you call a function, you need to call it with parentheses and optionally parameters (e.g. functionName(); instead of functionName). This applies to all JavaScript.

  2. Imagine there is one little gnome happily running through your code. When he gets to a line he reads it and does it. So let's say you've called clock(). He gets there and goes "what now? Oh, I have to go to clock()". So he goes to clock(). He gets there and goes "what now?" Oh, I have to go to clock()". See the pattern? He's going to keep doing this forever, but he never actually gets a chance to do the things that you want clock() to do, because the first thing he sees as soon as he reaches clock() is that he needs to go to clock(). This is called infinite recursion. What you really wanted was to say "every so often I want a little gnome to go to clock() and do the things in there" which is what setInterval does.

  3. $(s).appendTo('div') selects all things that match 's' (which will be nothing) and appends them to all things that match 'div' (which is every div). Instead, you want to select the div with 'someId': "$('#someId')", and append 's' to that: ".append(s);". If you don't want to append but instead replace, you will want to use ".html" not ".append".

Edits

  • Includes edits as per request.
  • Includes the fixes to 'setInterval' and 'var time' which slipped past me as per Anurag's answer. I'm not trying to take credit for these fixes, but just wanted to include as part of a comprehensive answer given the other changes to meet the OP's comment.


A few notes I made while adding your code on jsfiddle:

  1. Why call clock() inside clock without any base condition. It will run into an infinite loop. I've commented it out.
  2. time = new Date() adds time to the global object. You should probably add a var before it to keep things local to the function.
  3. When setInterval is called with the string "clock()" as a parameter, a ReferenceError gets thrown because clock is only defined in the outer anonymous function. However, when the inline code "clock()" is actually executed, it has no knowledge of the scope of that anonymous function, or the clock function. You should pass a reference to the function object itself, instead of passing a string, so when the timeout occurs, the reference is intact.
  4. Why did you put a self.setInterval()? I couldn't see self being declared anywhere else. Unless self is pointing to window or it's your custom object wrapper around window.setInterval, that will throw a ReferenceError because you are calling a method on an undefined object (self).

Updated Code:

$(document).ready(function() {  
    function clock() {
        // clock(); // infinite loop
        var time = new Date();  // global leak
        var s = "<p>" + time + "</p>";
        $(s).appendTo("div");
    }

    setInterval(clock, 1000); // self?

    $("button").click(function() {  
        clock(); // call function
    });        
});


If you are trying to execute clock() in intervals after the button click then you can do something like this

    $(function()   
    {   
        $("button").click(function()   
        {   
            setInterval (clock, 1000);   
        });   
        function clock()   
        {   
            time=new Date();   
            var s = "<p>" + time + "</p>";   
            $(s).appendTo("div");   
        } 
    });

This will run clock() at an interval of 1000 when the button is clicked.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜