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 语句似乎只适用于首先出现的链接,并且所有以下链接的样式都相同。第二个“蓝色”组与第一个相同,但顺序交换了。

我的做法显然不对。是否可以在每个元素上有条件地应用黄色类(基于 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 回答