2017-07-12 37 views
0

我有一個img標籤像如何使用JavaScript .replace()方法

<img src="Mesothelioma_image_1.jpg"/> 

我想要的東西來取代這個標籤就像

<amp-img class="blog-image" src="Mesothelioma_image_1.jpg" width="50" height= "20" layout="responsive"></amp-img> 

,以取代 HTML標籤通過保持相同src屬性值。

+1

你嘗試過什麼到目前爲止...? –

+0

img標籤內的另一個具有已知ID的HTML標籤? –

+0

['replaceWith'](http://api.jquery.com/replacewith/) – Tushar

回答

0

請參閱下面的代碼。

您將需要使用父類或Id訪問img。 我已經在鏈接點擊事件上做了這項工作,您可以在document.ready或任何其他事件上做到這一點。

jQuery('.clickMe').click(
 
function(e){ 
 
    e.preventDefault(); 
 
    var img = jQuery('.parent img').attr('src'); 
 
    var newhtml='<amp-img class="blog-image" src="'+img+'" width="50" height= "20" layout="responsive"></amp-img>'; 
 
    // console.log('IMG: '+ img); 
 
    
 
    jQuery('.parent').html(newhtml); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="parent"> 
 
    <img src="https://mosthdwallpapers.com/wp-content/uploads/2016/08/Pakistan-Flag-Image-Free-Download.jpg"/> 
 
</div> 
 
<a class="clickMe" href="#">Click Me </a> 
 

 
<amp-img class="blog-image" src="Mesothelioma_image_1.jpg" width="50" height= "20" layout="responsive"></amp-img>

+0

他不需要使用父類或標識來訪問它。看看我對[問題]的評論(https://stackoverflow.com/questions/45057562/how-to-replace-an-img-html-tag-using-js-replace-method#comment77088423_45057562)。 –

+0

從這行刪除'.parent' var img = jQuery('。parent img')。attr('src'); ' –

0

您可以使用querySelector()找到圖像。如果圖像包含一個id屬性會更容易。

然後,使用createElement()按名稱amp-img創建dom元素。

使用setAttribute()爲新元素(如class,src,width,erc)分配屬性。

使用insertBefore()將新元素添加到頁面中,並刪除舊圖像元素remove()

注意:我選擇舊圖像及其src,請根據您的需要更改它。

var oldImage = document.querySelector('img[src="Mesothelioma_image_1.jpg"]'); 
 

 
var newImage = document.createElement('amp-img'); 
 
newImage.setAttribute("class","blog-image"); 
 
newImage.setAttribute("src", oldImage.getAttribute('src')); 
 
newImage.setAttribute("width","50"); 
 
newImage.setAttribute("height","20"); 
 
newImage.setAttribute("layout","responsive"); 
 
oldImage.parentNode.insertBefore(newImage, oldImage); 
 
oldImage.parentNode.removeChild(oldImage); 
 

 
console.log(document.querySelector('amp-img[src="Mesothelioma_image_1.jpg"]')); // to find the appended new image
<img src="Mesothelioma_image_1.jpg"/>