我有一个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
属性值。
我有一个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
属性值。
请参阅下面的代码。
您将需要使用父类或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>
他不需要使用父类或标识来访问它。看看我对[问题]的评论(https://stackoverflow.com/questions/45057562/how-to-replace-an-img-html-tag-using-js-replace-method#comment77088423_45057562)。 –
从这行删除'.parent' var img = jQuery('。parent img')。attr('src'); ' –
您可以使用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"/>
你尝试过什么到目前为止...? –
img标签内的另一个具有已知ID的HTML标签? –
['replaceWith'](http://api.jquery.com/replacewith/) – Tushar