問題描述
我有一個包含文本和圖像的 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 字符串中獲取屬性值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!