2012-08-07 62 views
0

我只想在我的站點的一個頁面上執行一個函數,其中body的ID爲#modulePage16460412。我有下面的腳本不起作用。如果body id是一個特定值,則執行函數

<script type="text/javascript"> 
if($('#modulePage16460412').length > 0) { 
$(function() 
{ 
$(window).bind('load', 
    function(e) 
    { 
    window.setTimeout(function() 
     { 
     $.colorbox({opacity:0.3, href:"/storage/support/colorbox/offer.html"}); 
     }, /*timeout->*/ 2000); 
    }); 
}); 
} 
</script> 

難道也有可能只執行的功能,他們訪問的網頁,如果他們回來到該頁面不再執行的第一次?

任何幫助,將不勝感激。

+1

爲什麼不在腳本中使用此函數,只能將其添加到應該使用它的頁面上的HTML中? – 2012-08-07 17:26:50

+0

問題的第二部分需要使用cookie或localStorage。在這種情況下,我更喜歡localStorage,因爲服務器真的不關心這些信息,爲什麼它應該存儲在cookie中併發送到服務器。localStorage只存在於客戶端上。 – rlemon 2012-08-07 17:33:22

+0

完美的解決方案scott.korin!絕對是一個「爲什麼我沒有想到」的時刻:)謝謝! – Travis 2012-08-07 17:42:01

回答

0

您需要將條件放在$(function(){之內,以便在JavaScript查詢(未加載的)DOM存在ID之前實際加載body標籤。

$(function(){ 
    if($('#modulePage16460412').length) { 

     ... 

    } 
}); 
0

您定義了一個函數,但不會調用任何地方。

所以把一切都放在一些函數和調用中。 ($('#modulePage16460412')),如果($('#modulePage16460412')。length> 0)替換this,因爲當jquery找不到id爲的元素時:#modulePage16460412,它將返回空陣列。 empty_array.length = 0,所以它永遠是真的。

$('document').ready(function(){ 

if($('#modulePage16460412')) { 
$(function() 
{ 
$(window).bind('load', 
    function(e) 
    { 
    window.setTimeout(function() 
     { 
     $.colorbox({opacity:0.3, href:"/storage/support/colorbox/offer.html"}); 
     }, /*timeout->*/ 2000); 
    }); 
}); 
} 

}); 
1

你可以把對身體的負荷與指定的ID選擇它的功能......如果沒有元素與此ID存在,那麼該功能將永遠不會觸發。

$('#modulePage16460412').load(function() { // this will not be called unless an element with that ID has loaded into the DOM 

    // ... your code here. 

}); 

,並在「單次執行」部分觸摸(這真的應該是一個新的問題......但喔好),你可以使用localStorage的堅持設置。

http://jsfiddle.net/rlemon/ET9Zg/

你的情況類似

if(!getData('someKey')) { 
    // ok so they have not been here. 
    setData('someKey', 1); // now set the data so this won't get hit again. 
} 
0

也許更簡單的方法?

$(document).ready(function() { // runs code only after DOM ready 
    if ($('#modulePage16460412').length > 0) { // runs code only if id found 
     window.setTimeout(function() { 
      $.colorbox({ opacity:0.3, href:"/storage/support/colorbox/offer.html" }); 
     }, 2000); 
    } 
}); 
相關問題