问题描述
我有一个包含文本和图像的 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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)