Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找<;的src属性值;img>;Javascript字符串中的标记_Javascript_Jquery_Html_Json - Fatal编程技术网

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

查找<;的src属性值;img>;Javascript字符串中的标记,javascript,jquery,html,json,Javascript,Jquery,Html,Json,我一直在尝试在包含动态生成/分配的HTML代码块的javascript变量中获取img标记中的“src” 例如: 我试图从博客文章的内容中获取博客文章的第一个图像,但这对一些有图像的文章不起作用。如何使用javascript或jQuery做到这一点而不失败?将$(post\u body)更改为$(post) 试一试 var post=“这是一张图片,这是一段您好这里我们有另一张图片”; var firstimg=$(post.find('img:first').attr('src'); 使用纯J

我一直在尝试在包含动态生成/分配的HTML代码块的javascript变量中获取img标记中的“src”

例如:

我试图从博客文章的内容中获取博客文章的第一个图像,但这对一些有图像的文章不起作用。如何使用javascript或jQuery做到这一点而不失败?

$(post\u body)
更改为
$(post)

试一试

var post=“这是一张图片,这是一段您好

这里我们有另一张图片”; var firstimg=$(post.find('img:first').attr('src');
使用纯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") : "";

也许您可以尝试将id添加到
img
标记中,然后访问它

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

这是一个纯js解决方案。

很晚了,但如果不想加载图像,请使用下面的

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

如果创建div元素,则在插入innerHTML时会加载远程图像,模板会阻止请求。

您指的是
post\u body
,而变量名为
post
。很抱歉,我相应地更改了问题的文本。”必须将“post”更改为“post_body”。这就是为什么我在准备这个问题时错误地使用了post_body。它在这里起作用:。失败的情况是什么?你找到解决方案了吗?对不起,我相应地更改了问题的文本。”必须将“post”更改为“post_body”。这就是为什么我在准备这个问题时错误地使用了post_body的原因。由于html字符串中有引号,所以$(post)会给出一个错误。需要另一种方式。图像标记无法预定义,它们是从联机源自动加载的。我们不能说字符串以div或p标记开头。这是完全不可预测的,不能用这个答案。嗯。。。为什么字符串以什么开头很重要?这段代码适用于任何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") : "";
var oImg = document.getElementById('myImg');
var attr = oImg.getAttribute('src');
var div = document.createElement('template');
div.innerHTML = post_body;