2011-06-16 75 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。文档准备就绪后,窗口加载将会发生,但这绝对不是一个最终解决乱码的所有解决方案。