javascript - jquery: what does "$(this)" exactly mean? -


i have program , works well. see here.

this code:

<div id="round"></div>  <style> #round{ position: absolute; width: 200px; height: 200px; border-radius: 50%; left: 400px; top: 200px; background-color: #e1e1e1; } </style>  <script src="jquery.js"></script> <script src="jquery.easing.1.3.js"></script> <script> $(document).ready(function(){     $("#round").click(function(){         setinterval(function(){             $("#round").animate(                 {height: 250,                 width: 150,                 top:150,                 left: 425},                 {duration: 300}                 ).             animate(                 {height: 200,                 width: 200,                 top:200,                 left: 400},                 {duration: 300}             );         }, 0);     }); }); </script> 

but when change "#round" "this". won't work. why? (actually works, when put them setinterval(), won't work)

$(document).ready(function(){     $("#round").click(function(){         setinterval(function(){             $("#round").animate(                 {height: 250,                 width: 150,                 top:150,                 left: 425},                 {duration: 300}                 ).             animate(                 {height: 200,                 width: 200,                 top:200,                 left: 400},                 {duration: 300}             );         }, 0);     }); }); 

change "this", won't work.

$(document).ready(function(){     $("#round").click(function(){         setinterval(function(){             $(this).animate(                 {height: 250,                 width: 150,                 top:150,                 left: 425},                 {duration: 300}                 ).             animate(                 {height: 200,                 width: 200,                 top:200,                 left: 400},                 {duration: 300}             );         }, 0);     }); }); 

this reference member invokes current function...

then can wrap in jquery function $() select selector.

so setinterval calls anonymous function not invoked referencable member, defaults window object.

save this context in variable , use internally this...

$(document).ready(function(){     $("#round").click(function(){         var clicked = this;   //<----store click context outside setinterval         setinterval(function(){             $(clicked).animate(  //<----------use here                 {height: 250,                 width: 150,                 top:150,                 left: 425},                 {duration: 300}                 ).             animate(                 {height: 200,                 width: 200,                 top:200,                 left: 400},                 {duration: 300}             );         }, 0);     }); }); 

Comments