当img src不为空时如何添加rel属性?

时间:2014-11-18 13:27:36

标签: jquery add attr prettyphoto rel

<div class="otherProducts">
  <a href="http://metroplastasansor.bilginet.com/wp-content/uploads/2014/11/hidrolik-tampon-metroplast-asansor-41943-390057037-b.jpg" class="otherLink"><img src="http://metroplastasansor.bilginet.com/wp-content/uploads/2014/11/hidrolik-tampon-metroplast-asansor-41943-390057037-b.jpg" class="productThumb"></a>
  <a href="" class="otherLink"><img src="" class="productThumb"></a>
  <a href=""><img src="" class="productThumb"></a></div>

如何添加rel =&#34; prettyPhoto [gallery]&#34;与jquery?只有非空src的链接!

5 个答案:

答案 0 :(得分:2)

如果我理解正确,您正在寻找

$('a').filter(function() {
    return $(this).has('img[src!=""]');
})
.attr('rel', 'prettyPhoto[gallery]');

DEMO

答案 1 :(得分:1)

您可以使用.filter()

我选择了.otherProducts的所有图片。然后我传递一个函数来过滤,如果src属性是真值则返回true,如果它有一个虚假(空白)值,则返回false。

然后使用.attr()将最近的rel的{​​{1}}属性更改为剩余的选择:

<a>

JSFiddle

答案 2 :(得分:0)

我可以使用这段代码:

$('.otherProducts img').filter(function(){
return $(this).attr('src');}).parent().attr('rel', 'prettyPhoto[gallery]');

感谢乔治!

答案 3 :(得分:0)

使用.each.parent()之类的:

&#13;
&#13;
 $('.productThumb').each(function() {
   if ($(this).attr("src") != "") {
     //if it has source
     $(this).parent().attr("rel", "prettyPhoto[gallery]");
   }
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="otherProducts">
  <a href="http://metroplastasansor.bilginet.com/wp-content/uploads/2014/11/hidrolik-tampon-metroplast-asansor-41943-390057037s-b.jpg" class="otherLink">

    <img src="http://metroplastasansor.bilginet.com/wp-content/uploads/2014/11/hidrolik-tampon-metroplast-asansor-41943-390057037-b.jpg" class="productThumb">

  </a>
  <a href="" class="otherLink">
    <img src="" class="productThumb">
  </a>
  <a href="">
    <img src="" class="productThumb">
  </a>

</div>
&#13;
&#13;
&#13;

http://jsfiddle.net/5gnettxg/

答案 4 :(得分:-1)

试试这段代码

if($("img.productThumb").attr("src")!=""){

  $(this).attr("rel","prettyPhoto[gallery]");

}