2017-08-24 106 views
2

如何使用jQuery替換屬性relclass,還應該更改該值。所以我只想刪除href中的所有rel,並將其替換爲class屬性,但只在特定的div內並且只有當它包含圖像時才替代它。使用jQuery替換屬性rel與類 - 更改值

例如:

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

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

'$(」框一個:第一個孩子」)。 removeAttr(「rel」);'將刪除你的'rel'屬性。 '$(「。box a:first-child」)。addClass(「lightbox」);'將添加類。 –

+1

@OmSao我認爲你應該用'$(「。box a img」)。parent()'來代替'$(「。box」)'來得到想要的結果。 – EvilDevil

+0

@惡魔惡魔:謝謝夥伴,剛剛做到了! –

回答

0

你可以試試我在評論中提及,在可以inspect element並檢查類添加到顯示red彩色文本的頁面:

<!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>

+0

OP表示,「我只是想刪除所有在href中的rel並用class屬性替換它」,您將刪除rel並且不將該值設置爲類。您正在添加一個新班級。 –

+0

讓我編輯我的答案。感謝您指出! –

0

這應該做

$(".box a:has(img)").attr("class", function(){ 
 
    var val = $(this).attr("rel"); 
 
    $(this).removeAttr("rel"); 
 
    return val; 
 
}); 
 
console.log($(".box")[0].outerHTML)
<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>