2012-01-25 7 views
0

私は完全にこの問題を抱えています。私は、2つのスタイルシートがWordPressテーマの先頭部分にロードされているかどうかをチェックし、両方の外部スタイルシートが最初にロードされた場合にのみ内部スタイルシートをロードするスクリプトを作成しています。しかし、両方の外部スタイルシートが存在するかどうかをチェックする最後のifステートメントは、ifステートメントがまったくラップされていないかのように動作します。コードでは、私はこのアイデアを得たWebサイトについて言及します。私のコードは以下の通りです:JQuery(Javascript)でif文が無視されています

jQuery(document).ready(function() { 
/* Place smaller widget design behind .widgettitle only on 3-column layout */ 
/* adapted from http://churchm.ag/dynamically-applying-stylesheets-using-jquery/ */ 
//templateDir is defined in functions.php and placed into this theme's head tag 
var threeColExists = false; 

    // check for blue stylesheet with 3-column stylesheets 
    var blueExists = false; 
    jQuery('link').each(function() { 
     if(jQuery(this).attr('href') === 
     templateDir + '/layouts/3-column-right.css' || 
     templateDir + '/layouts/3-column-left.css' || 
     templateDir + '/layouts/3-column-right-magazine.css' || 
     templateDir + '/layouts/3-column-left-magazine.css') { 
      threeColExists = true; 
     } 
     if(jQuery(this).attr('href') === templateDir + '/styles/blue.css') { 
      blueExists = true;  
     } 
    }); 

    // This is what is getting executed regardless of whether the two conditions below evaluate to true 
    if((threeColExists === true) && (blueExists === true)) { 
     jQuery('head').append('<style type="text/css"> .widgettitle { background: url(' + templateDir + '/images/widget-design-smaller-blue.png) bottom left no-repeat #FFFFFF; } </style>'); 
    } 
}); 

答えて

2

コンパイルの比較はできません。毎回jQueryオブジェクトなしとhrefの値を再作成することなく、効率的に

if(jQuery(this).attr('href') === (templateDir + '/layouts/3-column-right.css') || 
    jQuery(this).attr('href') === (templateDir + '/layouts/3-column-left.css') || 
    jQuery(this).attr('href') === (templateDir + '/layouts/3-column-right-magazine.css') || 
    jQuery(this).attr('href') === (templateDir + '/layouts/3-column-left-magazine.css')) 

以上:それはあなたが、個々の平等のテストを綴るところ、次のようでなければならないであろう

var href = this.href; 
if (href === (templateDir + '/layouts/3-column-right.css') || 
    href === (templateDir + '/layouts/3-column-left.css') || 
    href === (templateDir + '/layouts/3-column-right-magazine.css') || 
    href === (templateDir + '/layouts/3-column-left-magazine.css')) 

または多分、この

if (this.href.match(new RegExp(templateDir + "/layouts/3-column-(right|left)(-magazine)?\\.css$"))) 
+0

第2の提案を使用するようにコードを変更しても機能します。私がしなければならなかった唯一の調整は、各jQueryの 'link'関数の隣にthreeColExists変数を移動することでした(何らかの理由で、変数が他の場所で宣言されたときには機能しませんでした)。どうもありがとうございました。 –

関連する問題