如何通过jquery从html中获取图像标记

时间:2011-09-22 16:33:27

标签: javascript jquery

所以我有一个数据集在变量entry.content:

中返回这样的东西
<p style="float:right;margin:0 0 10px 15px;width:240px"> <img src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p>

我如何通过jquery从中获取img src url?

4 个答案:

答案 0 :(得分:2)

<德尔> 假设您只有一个图像:     var sourceUrl = $('img')。attr('src');
var sourceUrl = $(entry.content).find('img').attr('src');

答案 1 :(得分:0)

你应该给你的图像一个Id并使用id选择器(这样你知道它只是你得到的那个元素)。您可以在纯文本(未添加到DOM)上运行查询代码,如下所示:

string plainText = '<p style="float:right;margin:0 0 10px 15px;width:240px"> <img id="theImg" src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p>'

var url = $(plainText).find('#theImg').attr('src');

或者,如果你不能修改它,而只是修改字符串中的那个图像:

var url = $(plainText).find('img').attr('src');

答案 2 :(得分:0)

如果您没有任何其他尺寸相同的图片:

$('img[width="240"]').attr('src');

答案 3 :(得分:0)

如果是我,我只需要regex replace来从变量中获取源代码:

entry.content = entry.content.replace("/src=\"(.+?)\"/i", "\1");

(虽然你不想使用。+;我只是懒得找到可能的URL字符)。如果您不确定entry.content是否会使用该格式,那么我会将其添加到隐藏div中的DOM中并从中获取源代码:

var hiddenDiv = $(document.body).add("div");
hiddenDiv.css("display", "none");
hiddenDiv.html(entry.content);
entry.content = hiddenDiv.find("img")[0].src;

当然,这是一个更危险的方法,因为它让你对XSS开放,但如果你信任源,你就可以做到。