Using javascript/jQuery to get attribute values from an HTML string(使用 javascript/jQuery 从 HTML 字符串中获取属性值)
问题描述
我有一个包含文本和图像的 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 字符串中获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 javascript/jQuery 从 HTML 字符串中获取属性值
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
