簡體   English   中英

使用javascript / jQuery從HTML字符串中獲取屬性值

[英]Using javascript/jQuery to get attribute values from an HTML string

我有一個包含文本和圖像的HTML字符串,例如

<p>...</p>
<img src="..." />
<p>...</p>

我需要獲取第一個圖像的src屬性。 圖像可能會或可能不會在<p>之后出現,並且可能存在多個圖像,或者根本沒有圖像。

最初,我嘗試將字符串附加到DOM並進行過濾。 但是,如果我這樣做,瀏覽器會請求所有外部資源。 在我的情況下,這增加了許多不必要的開銷。

我的初步方法:

var holder = $('<div></div>'); 

holder.html(content);

var src = holder.find('img:first').attr('src'); 

如何在不附加HTML的情況下獲取第一張圖像的src? 我需要使用正則表達式,還是有更好的方法?

解決方案需要基於javascript / jQuery - 我沒有使用任何服務器端語言。

我的問題非常類似於: http//forum.jquery.com/topic/parsing-html-without-retrieving-external-resources

謝謝

這個

$("<p><blargh src='whatever.jpg' /></p>").find("blargh:first").attr("src")

返回whatever.jpg所以我想你可以試試

$(content.replace(/<img/gi, "<blargh")).find("blargh:first").attr("src")

編輯

/<img/gi而不是"<img"

這應該工作:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        //Document Ready: Everything inside this function fires after the page is loaded
        $(document).ready(function () {
                    //Your html string
            var t = "<p><img src='test.jpg'/></p>"
            alert($(t).find('img:first').attr('src'));
        });
    </script>
</head>
<body>
</body>
</html>

我通常使用以下內容:

$(content).attr("src")
where 
content = "img src='/somesource/image.jpg'>" //removed < before img for html rendering in this comment

我解決了同樣的問題,試圖從iframe中取出src網址。 這是一個純JavaScript函數,適用於任何字符串:

function getSourceUrl(iframe) {
  var startFromSrc = iframe.slice(iframe.search('src'));
  return startFromSrc.slice(5, startFromSrc.search(' ') - 1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM