2011-06-16 74 views
0

我的代碼加載最需要被加載,以便其他的代碼之前,它才能正常工作。爲了讓我實現這個目標,我一次又一次地使用了多個腳本。有沒有辦法可以清理這些?我將盡力並給予例子:試圖鞏固jQuery代碼

//This needs to load first to add class 
<script> 
$(function(){ 
if (typeof(global_Current_ProductCode) !="undefined") 
    { 
     if ($('#pt494').length == 0) 
      { $('font[class="text colors_text"]:eq(0)').closest('table').addClass('thePrices'); }  
    } 
}); 
</script> 

//This needs to load 2nd because it has to add the class first before it does this 
<script> 
$(function(){ 
if (typeof(global_Current_ProductCode) !="undefined") 
    { 
     if ($('#pt490').length == 0) 
      { $('table[class="thePrices"]:eq(0)').closest('table').before($('font[class="productnamecolorLARGE colors_productname"]:eq(0)').addClass('toptitle'));} 
    } 
}); 
</script> 

有這麼多的代碼與此類似,也一定是把它扔到都在相同的IF語句的方法嗎?

+2

嗯,只是將它們放入同一'$(函數())'彼此下方(甚至下方彼此在同一個if語句)應該足夠了。或者我誤解了你的問題? – 2011-06-16 21:02:45

+0

沒有根據我有限的DOM樹的知識,它是一個非常基本的問題if語句= P – ToddN 2011-06-16 21:06:30

回答

2

我不知道我理解你的問題。按順序寫入的代碼塊不會同時執行。因此,你可以鞏固你的代碼如下所示:

<script> 
$(function(){ 
if (typeof(global_Current_ProductCode) !="undefined") 
    { 
     if ($('#pt494').length == 0) 
     { 
      $('font[class="text colors_text"]:eq(0)').closest('table').addClass('thePrices'); 
     } 
     if ($('#pt490').length == 0) { 
      $('table[class="thePrices"]:eq(0)').closest('table').before($('font[class="productnamecolorLARGE colors_productname"]:eq(0)').addClass('toptitle')); 
     } 
    } 
}); 
</script> 
+0

右,我需要他們根據我的劇本我現在有爲了去此起彼伏,層出不窮,幾乎像..這似乎可以工作我會做更多的測試和回來,謝謝。 – ToddN 2011-06-16 21:08:14

+0

是的,你會得到順序執行(一個接一個)與上述。 – 2011-06-16 21:13:59

0

短設計自己的框架,沒有什麼可以做,除了在將來嘗試編寫更乾淨的代碼。根據我的經驗,我通常會將所有html注入內容整合到一個函數中,並在其他任何函數之前調用它。

你也可以獨立的功能出來的$(document)。就緒()和$(窗口).load。文檔準備就緒後,窗口加載將會發生,但這絕對不是一個最終解決亂碼的所有解決方案。