简体   繁体   中英

Trying to make a JQuery plugin not working

I am trying something new for me.I am always making html pages with the same functions so I want to simplify my work using a JQuery plugin made by me.But this is the First time I am trying this and I have read many web pages on how to do this and I don't know what doesn't work.This is Emu.js file:

   $.fn.loop = function(time,callback) {
       setInterval(this,time);
       if(callback !== 'undefined' && typeof(callback) == "function") {
           callback
       }
   };

And this is Emu.html file:

   <!DOCTYPE html>
   <html>
   <head>
       <script src="JQuery.js" ></script>
       <script src="Emu.js" ></script>
   </head>
   <body onload="do_it()">
       <p></p>
       <script type="text/javascript">
           function hello() {
               $("p").append("Hello!"+"<br>")
           }

           function do_it() {
               $(hello).loop(2000)
           }
       </script>
   </body>
   </html>
  • jQuery plugins/ Methods (just like .show() ) expect a jQuery Element Object as reference: $("p").loop()
  • Put the setInterval stuff within your if
  • Use $.proxy to refer to the right jQuery this Element Object (otherwise this will point to window Object inside setInterval )
  • Inside the hello() feel free to use jQuery's $(this) cause this refers to the JS reference on the HTMLParagraphElement "p"

 $.fn.loop=function(time,callback) { if(callback !== 'undefined' && typeof callback === "function") { setInterval($.proxy(callback, this), time); } }; jQuery(function($) { // Use DOM ready instead of <body onload="do_it()"> function hello(){ $(this).append("Hello!<br>"); } $("p").loop(2000,hello); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p></p> 

Some errors you've could avoid your self are ie the use of WindowTimers.setInterval where the first parameter is supposed to be a callback function setIntarval(fn, time) . this is not a function in your case.

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