首页 > 解决方案 > 页面加载后功能未运行

问题描述

我有以下功能。当我使用单击事件侦听器调用它时,此函数可以完美运行。但是,我希望它在页面完成加载后执行。

我曾经使用以下方法在页面加载后调用该函数:

window.addEventListener("load",compSummary);

它曾经完美地工作。但是我最近在我的代码中更改了一些东西,现在它不再起作用了。如前所述:如果我使用不同的事件侦听器,则该函数有效,但如果我在页面完成加载后尝试加载它,则该函数无效。我的代码中有什么东西可以阻止它工作吗?或者我应该在页面加载后尝试不同的方式来运行该功能?

function compSummary() {
    var e = [];
    summaryWidgetList.innerHTML = "",
    document.querySelectorAll(".component").forEach(t => {
        var o = t.querySelector(".component_name"),
            n = t.querySelector(".component_text"),
            r = t.querySelector(".component_heading"),
            m = t.querySelector(".component_product"),
            c = t.querySelector(".component_qty");
        var i = null == n ? o.textContent.trimStart() : 
            null == c ? n.textContent : m.getAttribute("data-qty") + " x " + n.textContent;
        if("None" != i) {
            var u = document.createElement("li");
            u.innerHTML = "<b>" + r.textContent + "</b>:&nbsp;" + i, 
            summaryWidgetList.appendChild(u), 
            e.push(i)
        }
    }),
    PriceField.value = document.querySelector(".comp-price").textContent,
    SummaryField.value = [...e].join("\n"),
    document.querySelector("#comp-price-display").textContent = document.querySelector(".Price-amount").textContent
}

更新:

抱歉,最初没有在控制台中看到这个。我不知道这意味着什么。控制台显示如下: Uncaught TypeError: can't access property "textContent", o is null

它指向以下行:

var i = null == n ? o.textContent.trimStart() : 
    null == c ? n.textContent : m.getAttribute("data-qty") + " x " + n.textContent;

标签: javascript

解决方案


推荐阅读