使用javascript/jQuery从HTML字符串获取属性值 [英] Using javascript/jQuery to get attribute values from an HTML string
问题描述
我有一个包含文本和图像的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
My question is very similar to: 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/gi
而不是"<img"
这篇关于使用javascript/jQuery从HTML字符串获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!