簡體   English   中英

替換方法在瀏覽器中不起作用但在 console.log 中起作用

[英]replace method not working in browser but working in console.log

我正在嘗試替換Wordpress網站中的多次出現,所以這就是我所做的:

window.onload = init;

function init()
{
    // get all the divs which have specific class names
    let divElems = 
    document.querySelectorAll(".vc_custom_heading.white.vc_gitem-post-data.vc_gitem-post-data-source-post_title");

    // loop on the divs
    for(let i = 0 ; i < divElems.length ; i++)
    {
        // get the first child of the div : a <h2>
        let titleElem = divElems[i].childNodes[0];
        // get the first child of the title : a <a>
        let linkElem  = titleElem.childNodes[0];
        // get the text content of the link
        let text      = linkElem.textContent;

        // replace the word test by nothing
        text = text.replace(/test/g, '');
        // all the occurrences of test have been removed in the console.log, but not in browser
        console.log(text);
    }
};

但奇怪的是,replace 方法在console.log 中工作正常(我可以看到測試詞已被刪除),但在瀏覽器頁面中沒有任何變化!

有人有想法嗎? :)

ArbreMojo。

您只是在更新變量值,因此它不會更新實際的元素內容。 要使其工作,只需更新textContent屬性即可更新元素內容。

text = text.replace(/test/g, '');
linkElem.textContent = text;

暫無
暫無

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

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