質問

正しく動作するためには、他のコードの前にほとんどロードする必要があるコードがたくさんあります。私がこれを達成するために、私は何度も何度も複数のスクリプトを持っています。これのいくつかをきれいにする方法はありますか?例を挙げてみます:

//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>

これに似たコードが非常に多くありますが、同じ声明の下ですべてを投げる方法が必要ですか?

役に立ちましたか?

解決

私はあなたの質問を理解しているかどうかわかりません。順番に記述されたコードブロックは同時に実行されません。したがって、次のようにコードを統合できます。

<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>

他のヒント

独自のフレームワークを設計するだけでなく、将来クリーナーコードを作成しようとする以外にできることはあまりありません。私の経験では、私は一般的にすべてのHTMLインジェクションのものを単一の機能に統合し、何よりも前にそれを呼び出します。

また、関数を$(document).ready()および$(window).loadに分離することもできます。ドキュメントの準備ができた後にウィンドウの負荷が発生しますが、これは間違いなく乱雑なコードのすべてのソリューションではありません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top