在 Javascript 字符串中查找 <img> 标记的 src 属性值
Find src attribute value of <img> tag in a Javascript string
我一直在尝试在javascript变量中的img标签中获取"src",该变量包含动态生成/分配的HTML代码块。
例如:
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>"
"post"变量的内容不是预定义的,它是动态的,其中的HTML代码总是在变化。为了在其中获取图像的 src,我做了以下操作。但它并不总是对我有用。
var firstimg = $(post_body).find("img:first").attr("src");
我试图从博客文章的内容中获取博客文章的第一张图片,但这不适用于某些带有图像的帖子。如何使用javascript或jQuery来完成此操作而不会失败?
使用纯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") : "";
将$(post_body)
更改为$(post)
尝试
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');
也许您可以尝试将 id 添加到img
标签中,然后访问它。
var oImg = document.getElementById('myImg');
var attr = oImg.getAttribute('src');
这是一个纯粹的js解决方案。
晚了,但是,如果不想加载图像,请使用以下内容。
var div = document.createElement('template');
div.innerHTML = post_body;
如果创建div 元素,则在插入 innerHTML 时加载远程图像,模板会阻止请求。
相关文章:
- 从其他元素上的单击事件访问image src属性
- 使用json数据更改视频标签中的src属性
- 为什么html src属性中的相对url是因为Javascript函数中的完整路径
- 无法在
标记 SRC 属性中传递参数
- 单击没有 src 属性的 iframe 中的元素
- img src 属性在为空时返回页面的 URL
- 如何从浏览器隐藏视频src属性's检查元素
- 为什么当我尝试为iframe-src属性构建URL时,AngularJS会抛出错误
- Windows Phone浏览器控件执行JS函数来替换src属性
- 使用jQuery通过更改src属性来设置一个图像标签的动画
- 使用angularjs中的自定义服务交换ng src属性
- 使用angularjs交换图像标签中的ng-src属性
- AngularJS - 如何在 iframe 元素更改时读取 SRC 属性
- 浏览器检测和 Firefox data-src 属性
- 延迟加载引导传送带而不更改 img src 属性
- 根据 JSON 更改图像的 src 属性
- 如何在 ajax 请求的回调中设置 ngInclude 元素的 src 属性
- 如何制作 AngularJS 指令来更改图像的 src 属性
使用 Jquery 不会更改 src 属性
- 修改其<源>元素的 src 属性后,视频不会更新