0

我有大量代码需要在另一段代码之前加载,以使其正常工作。为了让我实现这一点,我一遍又一遍地编写了多个脚本。有什么办法可以清理一些吗?我将尝试举例:

//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 语句下吗?

4

2 回答 2

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>
于 2011-06-16T21:03:01.697 回答
0

除了设计自己的框架之外,除了尝试在未来编写更清晰的代码之外,您无能为力。根据我的经验,我通常将所有 html 注入内容合并到一个函数中,然后在其他任何事情之前调用它。

您还可以将函数分离为 $(document).ready() 和 $(window).load。文件准备好后会出现窗口加载,但这绝对不是解决混乱代码的全部解决方案。

于 2011-06-16T21:05:36.933 回答