【问题标题】:replace method not working in browser but working in console.log替换方法在浏览器中不起作用但在 console.log 中起作用
【发布时间】:2019-08-11 08:58:29
【问题描述】:

我正在尝试替换 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);
    }
};

但奇怪的是,替换方法在 console.log 中运行良好(我可以看到测试词已被删除),但在 浏览器 页面中没有任何变化!

有人有想法吗? :)

ArbreMojo。

【问题讨论】:

    标签: javascript wordpress browser replace console.log


    【解决方案1】:

    您只是在更新变量值,因此它不会更新实际的元素内容。要使其正常工作,只需更新 textContent 属性即可更新元素内容。

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

    【讨论】:

    • @ArbreMojo:很高兴它有帮助
    猜你喜欢
    • 2023-04-06
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2016-04-20
    • 2020-03-29
    • 2011-07-22
    • 2013-09-29
    相关资源
    最近更新 更多