加载特定div后调用Javascript中的函数[duplicate]

hrirmatl  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(123)
    • 此问题在此处已有答案**:

What is the difference between a function call and function reference?(6个答案)
How to access the webpage DOM/HTML from an extension popup or background script?(2个答案)
15小时前关门了。
我正在开发一个Chrome插件,我面临着一个挑战,我调用的函数使用一个变量通过类名获取元素。当函数在特定元素加载到DOM之前被调用时,变量返回undefined。
请看下面的代码-

(() => {
    let wfLeftControls;
    let currentProject = "";
    let dynButtons;

    const newProjectLoaded = async () => {
        const notesBtnExists = document.getElementsByClassName("notes-button")[0];

        if (!notesBtnExists) {
            const notesBtnElement = document.createElement("div");
            const notesBtnSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            const notesBtnPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');

            notesBtnElement.className = "button " + "top " + "notes-button ";
            /* active class highlights that the menu is active */

            notesBtnSvg.setAttribute('viewBox', '0 0 45 45');
            notesBtnSvg.setAttribute('fill', '#ffffff');
            notesBtnSvg.classList.add('bem-Svg');
            notesBtnSvg.setAttribute('style', 'display: block; position: relative;');

            notesBtnPath.setAttribute('d', 'M9 39h30V20.25L27.75 9H9v30Zm0 3q-1.25 0-2.125-.875T6 39V9q0-1.25.875-2.125T9 6h20l13 13v20q0 1.25-.875 2.125T39 42Zm4.95-8.55h20.1v-3h-20.1Zm0-7.95h20.1v-3h-20.1Zm0-7.95h13.8v-3h-13.8ZM9 39V9v30Z');
            notesBtnPath.setAttribute('fill', '#fffff');

            notesBtnSvg.appendChild(notesBtnPath);
            notesBtnElement.appendChild(notesBtnSvg);
            notesBtnElement.addEventListener("click", NotesPanelEventHandler);
            /* to open or close notes panel when user clicks icon */

            setTimeout(() => {

                wfLeftControls = document.getElementsByClassName("left-sidebar-links")[0];

                wfLeftControls.appendChild(notesBtnElement);

            }, 5000);
        }
    };

    chrome.runtime.onMessage.addListener((obj, sender, response) => {
        const { type, projectID } = obj;

        if (type === "NEW") {
            currentProject = projectID;
            newProjectLoaded();
        }
    });

    window.onload = newProjectLoaded();

})();

这里,newProjectLoaded()是被调用的函数。
由于代码在加载元素"left-sidebar-links"之前执行,因此变量wfLeftControls返回undefined
所以我设置了一个5秒的超时来解决这个问题。
有人能帮我在加载所有DOM元素或加载left-sidebar-links后如何调用这个函数newProjectLoaded();吗?
先谢了🙏

esyap4oy

esyap4oy1#

如果你需要等到DOM准备好(所有元素都已经添加到页面)使用事件“DOMContentLoaded”。
您使用了事件“load”,该事件在**“DOMContentLoaded”之后**激发。
问题是-您没有将newProjectLoaded设置为事件侦听器,您调用了函数,而调用结果被设置为侦听器:

// change this
window.onload = newProjectLoaded(); // function was called -> return undefined -> undefined set as event handler

// to this
window.onload = newProjectLoaded; // function set as event handler

相关问题