简体   繁体   English

查找 src 属性值<img> Javascript 字符串中的标记

[英]Find src attribute value of <img> tag in a Javascript string

I have been trying to get the 'src' in img tags inside a javascript variable that contains a block of HTML code dynamically generated/assigned.我一直试图在包含动态生成/分配的 HTML 代码块的 javascript 变量中获取 img 标签中的“src”。

Eg:例如:

var post_body = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>"

the content of the 'post' variable is not predefined and it is dynamic and the HTML code in it always changes. “post”变量的内容不是预定义的,它是动态的,其中的 HTML 代码总是在变化。 To get the src of the image in it, I did the following.为了在其中获取图像的 src,我执行了以下操作。 But it does not always work for me.但它并不总是对我有用。

var firstimg = $(post_body).find("img:first").attr("src");

I was trying to get the first image of a blog post from the blog post's content but this does not work for some posts having images.我试图从博客文章的内容中获取博客文章的第一张图片,但这不适用于某些包含图片的文章。 How can this be done using javascript or jQuery without failing?如何使用 javascript 或 jQuery 做到这一点而不会失败?

Using plain JavaScript, dump the HTML into a temporary element and extract it:使用普通的 JavaScript,将 HTML 转储到一个临时元素中并提取它:

var div = document.createElement('div');
div.innerHTML = post_body;
var firstImage = div.getElementsByTagName('img')[0]
var imgSrc = firstImage ? firstImage.src : "";
// or, if you want the unresolved src, as it appears in the original HTML:
var rawImgSrc = firstImage ? firstImage.getAttribute("src") : "";

Change $(post_body) to $(post)$(post_body)更改$(post_body) $(post)

Try试试

var post = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>";
var firstimg = $(post).find('img:first').attr('src');

Perhaps you can try adding id to img tag and then access it.也许您可以尝试将 id 添加到img标签然后访问它。

var oImg = document.getElementById('myImg');
var attr = oImg.getAttribute('src');

This is a pure js solution.这是一个纯js解决方案。

Late but, if don't want the images to be loaded use the below.晚了,但是,如果不想加载图像,请使用以下内容。

var div = document.createElement('template');
div.innerHTML = post_body;

if you create div element the remote images are loaded the moment you insert innerHTML, template prevents the requests.如果您创建 div 元素,则在您插入 innerHTML 时加载远程图像,模板会阻止请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM