Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何通过jquery从html获取图像标记_Javascript_Jquery - Fatal编程技术网

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

Javascript 如何通过jquery从html获取图像标记,javascript,jquery,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 adventur

因此,我有一个数据集,它在变量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从中获取imgsrc url

假设您只有一个图像: var sourceUrl=$('img').attr('src');
你应该给你的图像一个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');

如果没有任何其他大小相同的图像:

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

如果是我,我会用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敞开大门,但如果您信任源代码,您可以这样做。

但请注意,上面的数据是以纯文本形式发送的。虽然不像htmlAlthough那样,如果Shawn的方法(如上)不将其添加到DOM中,那么它会更安全;但是,在
上使用
find
#img
本身将不起作用,因为它只遍历子体。
$('img[width="240"]').attr('src');
var hiddenDiv = $(document.body).add("div");
hiddenDiv.css("display", "none");
hiddenDiv.html(entry.content);
entry.content = hiddenDiv.find("img")[0].src;