2012年6月14日 星期四

setTimeout 傳物件參數

先看一下一般 setTimeout 怎麼用


function hello(){alert('Hello!');}
setTimeout("hello()", 1000);

在指定 function 時是以字串方式編寫
若要傳靜態參數則用字串相加方式

function hello(text){alert(text);}
var hellostring = "Hello! Welcome to Earth!";
setTimeout("hello(" + hellostring + ")", 1500);

但是以這種方式在碰到要傳物件時就會出錯

function hello(a, e){
     $("#pop") .html("Welcom to " + a.children('span').first().text() + "").css({
           'top':e.pageY -10,
           'left':e.pageX + 20
     }).fadeIn();
}
$(function(){
     $(".pop").mouseenter(function(e){
           setTimeout("hello(" + this + "," + e  + ")", 1000);  //丟過去不是要的物件
     });
}) ;

    <@div id="pop" style="display:none;position:absolute">

    <@a href="http://google.com" class="pop">

        <@span>google

    <@/a>

    <@a href="http://yahoo.com" class="pop">

        <@span>yahoo

   

 要改寫成

setTimeout((function (a,e){ return function (){ hello(a,e); } })(this, e), 1000);

這樣才能以物件方式傳送

--
參考網頁
http://blog.longwin.com.tw/2011/12/javascript-settimeout-args-2011/

沒有留言:

張貼留言