0

hrefセットがない、または空白の場合は、すべてのリンクを強調表示しようとしています。私は次のように書いています:http://jsfiddle.net/nSMEf/

$(document).ready(function() {
  if ($('.green').attr("href") == "" || typeof $('.green').attr("href") === 'undefined'){
      $('.green').attr('class', 'yellow');
  }

  if ($('.blue').attr("href") == "" || typeof $('.blue').attr("href") === 'undefined'){
       $('.blue').attr('class', 'yellow');
  }
});

ifステートメントは、最初に来たリンクにのみ適用されるようであり、以降のすべてのリンクは同じスタイルになっていることに気付きました。2番目の「青」グループは最初のグループと同じですが、順序が入れ替わっています。

私のアプローチは明らかに正しくありません。各要素に条件付きで(hrefが空白かどうかに基づいて)黄色のクラスを適用することは可能ですか?

4

3 に答える 3

2

これは役に立ちますか

    $("a").each(function(){

       if(!($(this).attr("href")) || $(this).attr("href") == "") {
          $(this).addClass("yellow");
       }       
    });

更新された jsfiddle: http://jsfiddle.net/nSMEf/3/

コメントの提案に従って上記のコードを編集する

 $("a").each(function(){
    var self = $(this).attr("href");
    if(!(self) || self == "") {
        $(this).addClass("yellow");
    }        
});
于 2012-04-22T04:44:52.747 に答える
1

ひやデモhttp://jsfiddle.net/5ehtZ/ || _ http://jsfiddle.net/5ehtZ/2/

コード

$("a").each(function(){
    //do something with the element here.
    if (!($(this).attr("href")) || $(this).attr("href") == ""){
        // now blue and green diff is not needed because you append yellow if they are empty.
         $(this).attr('class', 'yellow');
    }

});
​
于 2012-04-22T04:48:20.103 に答える
1

待って..何?

jQueryセレクターは仕事をしませんか?

$('.blue[href=""]').addClass('yellow');

于 2012-04-22T04:57:13.187 に答える