我有一个包含文本和图像的 HTML 字符串,例如
I have an HTML string that contains text and images, e.g.
<p>...</p>
<img src="..." />
<p>...</p>
我需要获取第一张图片的 src 属性.图片可能出现在 <p> 之后,也可能不出现,并且可能有多个图片,或者根本没有图片.
I need to get the src attribute of the first image. The image may or may not come after a <p> and there could be more than one image, or no image at all.
最初,我尝试将字符串附加到 DOM 并进行过滤.但是,如果我这样做,浏览器会请求所有外部资源.在我的情况下,这会增加很多不必要的开销.
Initially, I tried appending the string to the DOM and filtering. But, if I do this the browser requests all of the external resources. In my situation, this adds a lot of unnecessary overhead.
我最初的做法:
var holder = $('<div></div>');
holder.html(content);
var src = holder.find('img:first').attr('src');
如何在不附加 HTML 的情况下获取第一张图片的 src?我需要使用正则表达式,还是有更好的方法?
How can I get the src of the first image without appending the HTML? Do I need to use a regular expression, or is there a better way?
解决方案需要基于 javascript/jQuery——我没有使用任何服务器端语言.
The solution needs to be javascript/jQuery based – I'm not using any server side languages.
我的问题非常类似于:http://forum.jquery.com/topic/parsing-html-without-retrieving-external-resources
谢谢
这个
$("<p><blargh src='whatever.jpg' /></p>").find("blargh:first").attr("src")
返回 whatever.jpg 所以我想你可以试试
returns whatever.jpg so I think you could try
$(content.replace(/<img/gi, "<blargh")).find("blargh:first").attr("src")
编辑
/ 而不是 "<img"
这篇关于使用 javascript/jQuery 从 HTML 字符串中获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)