jQuery 在 Javascript 字符串中查找 <img> 标签的 src 属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19207643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find src attribute value of <img> tag in a Javascript string
提问by TechyTee
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. To get the src of the image in it, I did the following. But it does not always work for me.
“post”变量的内容不是预定义的,它是动态的,其中的 HTML 代码总是在变化。为了在其中获取图像的 src,我执行了以下操作。但它并不总是对我有用。
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 做到这一点而不会失败?
回答by Niet the Dark Absol
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") : "";
回答by Tamil Selvan C
Change $(post_body)
to $(post)
更改$(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');
回答by TechyTee
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解决方案。
回答by Logesh R
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 时加载远程图像,模板会阻止请求。