簡體   English   中英

在來自服務器的(html)字符串中找到特定的 html 元素,而不將其附加到 dom

[英]find a specific html element in (html)string coming from server without appending it to the dom

我嘗試分析從服務器獲取的字符串,以確保內容符合我的預期。

我的目標:

  • 從我的廣告服務后端加載 html
  • 確保它是廣告,而不是某些錯誤頁面
  • 如果測試成功,則顯示 iframe 中的內容

我已經找到了 stackoverflow 的答案(見下面的代碼),但我失敗了。

我的測試 html

<!DOCTYPE html>
<html lang="en">
    <head><title>Test ad</title></head>
    <body>
        <img id="promo_news" src="test-ad-pic0.png" alt="Test ad">
    </body>
</html>

我測試檢索到的 html 的代碼:

function isLoadedHtmlAnAd(loadedHtmlCode) {

    // trim is necessary to get rid of a jquery error when checking the string 
    // in isLoadedHtmlAnAd(see: https://stackoverflow.com/a/23061815)
    loadedHtmlCode= loadedHtmlCode.trim(); 


    // inspired by https://stackoverflow.com/a/15403888
    let tempDom = $.parseHTML(loadedHtmlCode);
    let markerElement = $('#promo_news', tempDom);

    if(markerElement.length > 0) {
        return true;
    } else {

        // inspired by https://stackoverflow.com/a/28726480
        tempDom = $(loadedHtmlCode);
        let markerElement = tempDom.find('#promo_news');
        if(markerElement.length > 0) {
            return true;
        }
    }
    return false;
}

問題是找不到 markerElement。

我可以看到加載的 html 是正確的,並且包含帶有 id #promo_news 的 img 標簽

知道我做錯了什么嗎? 我也對如何檢測 html 是否是廣告的其他想法持開放態度。

謝謝!

我的代碼中提到的stackoverflow答案可以點擊

我錯過了其中一個鏈接答案中的解決方案。

我寫

let tempDom = $.parseHTML(loadedHtmlCode);
let markerElement = $('#promo_news', tempDom);

這有效

let tempDom = $('<output>').append($.parseHTML(loadedHtmlCode));
let markerElement = $('#promo_news', tempDom);

https://stackoverflow.com/a/15403888

暫無
暫無

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

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