[英]Find src attribute value of <img> tag in a Javascript string
我一直試圖在包含動態生成/分配的 HTML 代碼塊的 javascript 變量中獲取 img 標簽中的“src”。
例如:
var post_body = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>"
“post”變量的內容不是預定義的,它是動態的,其中的 HTML 代碼總是在變化。 為了在其中獲取圖像的 src,我執行了以下操作。 但它並不總是對我有用。
var firstimg = $(post_body).find("img:first").attr("src");
我試圖從博客文章的內容中獲取博客文章的第一張圖片,但這不適用於某些包含圖片的文章。 如何使用 javascript 或 jQuery 做到這一點而不會失敗?
使用普通的 JavaScript,將 HTML 轉儲到一個臨時元素中並提取它:
var div = document.createElement('div');
div.innerHTML = post_body;
var firstImage = div.getElementsByTagName('img')[0]
var imgSrc = firstImage ? firstImage.src : "";
// or, if you want the unresolved src, as it appears in the original HTML:
var rawImgSrc = firstImage ? firstImage.getAttribute("src") : "";
將$(post_body)
更改$(post_body)
$(post)
試試
var post = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>";
var firstimg = $(post).find('img:first').attr('src');
也許您可以嘗試將 id 添加到img
標簽然后訪問它。
var oImg = document.getElementById('myImg');
var attr = oImg.getAttribute('src');
這是一個純js解決方案。
晚了,但是,如果不想加載圖像,請使用以下內容。
var div = document.createElement('template');
div.innerHTML = post_body;
如果您創建 div 元素,則在您插入 innerHTML 時加載遠程圖像,模板會阻止請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.