Javascript 如何通过jquery从html获取图像标记
因此,我有一个数据集,它在变量entry.content中返回如下内容: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
<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;