使用jQuery用class替换属性rel - 同时更改值

时间:2017-08-24 11:49:02

标签: jquery

如何使用jQuery将属性rel替换为class,还应更改该值。所以我只想删除rel中的所有href并将其替换为class属性,但只能在某个div内,并且仅在包含图片的情况下?< / p>

例如:

<div class="box">
   <a href="#" rel="lightbox123">
      <img src="#">
   </a>
</div>

<div class="box">
   <a href="#" class="lightbox">
      <img src="#">
   </a>
</div>

2 个答案:

答案 0 :(得分:0)

这应该

&#13;
&#13;
$(".box a:has(img)").attr("class", function(){
   var val = $(this).attr("rel");
   $(this).removeAttr("rel");
   return val; 
});
console.log($(".box")[0].outerHTML)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
   <a href="#" rel="lightbox123">
      <img src="#">
   </a>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以尝试我在评论中提到的内容,在您可以inspect element的页面中检查是否已添加该课程以red颜色显示文字:

&#13;
&#13;
<!DOCTYPE html>
<html>
  <head>
   <style>
    .lightbox{color: red;}
   </style>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
    $(document).ready(function(){

    var getTagName = $(".box a:has(img)").parent();  //returns DIV, as $(".box a:has(img)") returns ANCHOR tag

       //$(".box a:first-child").removeAttr("rel"); //this will remove rel attribute from first child of box class without checking if anchor tag has child as img, hence not good.
       //$(".box a:first-child").addClass("lightbox"); // this will add class to the first child without checking img tag, hence not recommendable
         if(getTagName.prop("tagName")=="DIV") //Note that tagName returned in CAPS
         {
           $(".box a:has(img)").removeAttr("rel").addClass("lightbox");// This removes rel attribute
         }

     });
    </script>
  </head>
<body>

<div class="box">
   <a href="#" rel="lightbox123">
      <img src="#" alt="alternate text">
   </a>
</div>

</body>
</html>
&#13;
&#13;
&#13;