You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击触发openModal()提示未定义问题求助

问题:点击添加用户图标时提示openModal() is not defined

问题根源

你的add-user-modal.ejs中的JavaScript代码存在语法错误和逻辑错误,导致整个脚本无法正常执行,进而使得openModal函数没有被正确注册到全局作用域:

  • 全局作用域中直接使用await,这在非模块脚本中属于语法错误,会中断脚本执行
  • 表单提交的处理代码被错误地放在全局作用域,页面加载时就会执行,而非表单提交时触发

解决方案

步骤1:修复add-user-modal.ejs的脚本错误

将表单提交相关的逻辑全部移入form.onsubmit的异步回调函数中,确保await在合法的上下文使用,同时修正其他DOM操作的语法错误:

<div class="modal-wrapper" id="add-user-modal">
    <div class="modal">
        <a href="#" onclick="closeModal()" class="modal-close">+</a>
        <div class="modal-title">
            <h2>Create New User</h2>
        </div>
        <div class="modal-body">
            <form method="post" action="/users" enctype="multipart/form-data" id="add-user-form">
                <input type="text" placeholder="enter name" name="name" />
                <p class="error name-error"></p>
                <input type="text" placeholder="enter email" name="email" />
                <p class="error email-error"></p>
                <input type="text" placeholder="enter mobile" name="mobile" />
                <p class="error mobile-error"></p>
                <input type="password" placeholder="enter password" name="password" />
                <p class="error password-error"></p>
                <input type="file" name="avatar" />
                <p class="error avatar-error"></p>
                <p class="error common-error"></p>

                <input type="submit" value="Submit" />
            </form>
        </div>
    </div>
</div>
<script>
    console.log('Hello from console');

    const modal = document.querySelector("#add-user-modal");
    const form = document.querySelector("#add-user-form");
    
    function closeModal() {
        modal.style.display = "none";
    }

    function openModal() {
        modal.style.display = "block";
    }

    // success toast
    const successToast = Toastify({
        text: "User was added successfully. Reloading the list...",
        duration: 1000
    })

    // form submit handler - 修正:将所有处理逻辑移入回调内
    form.onsubmit = async function (event) {
        event.preventDefault();

        // clear all the error first
        const errorPlaceHolder = document.querySelectorAll("p.error");
        for (let index = 0; index < errorPlaceHolder.length; index++) {
            errorPlaceHolder[index].style.display = "none";
        }

        const inputErrors = document.querySelectorAll("input.error");
        if (inputErrors.length > 0) {
            for (let index = 0; index < inputErrors.length; index++) {
                inputErrors[index].classList.remove("error");
            }
        }

        // prepare the form data
        const formData = new FormData(form);

        // send the request to server 
        let response = await fetch("/users", {
            method: "POST",
            body: formData,
        });

        // get response
        let result = await response.json();

        // handle error and response
        if (result.errors) {
            //errors
            Object.keys(result.errors).forEach((fieldName) => {
                // 修正:form[fieldName] 获取表单控件,classList 首字母大写
                form[fieldName].classList.add("error");

                // set all error to the place holder text content
                const errorPlaceHolder = document.querySelector(`.${fieldName}-error`);
                errorPlaceHolder.textContent = result.errors[fieldName].msg;

                // make all place holder visible
                errorPlaceHolder.style.display = "block";

            });
        } else {
            // success
            successToast.showToast();
            closeModal();
            // 修正:语法错误,正确获取元素后设置样式
            document.querySelector("p.error").style.display = "none";

            // reload the page after one second
            setTimeout(() => {
                location.reload();
            }, 1000);
        }
    }
</script>

步骤2:可选优化:改用事件委托绑定点击事件

如果不想依赖全局函数,可以在user.ejs的</body>前添加脚本,用事件委托绑定点击事件,避免全局函数依赖:

<script>
    document.addEventListener('click', function(e) {
        if(e.target.closest('.new-user a')) {
            e.preventDefault();
            document.querySelector("#add-user-modal").style.display = "block";
        }
    });
</script>

然后移除user.ejs中a标签的onclick="openModal()"属性。

额外说明

  • 确保Toastify已经正确引入(页面中加载了Toastify的JS和CSS),否则会出现Toastify is not defined的新错误
  • 修正后的脚本解决了以下语法错误:
    • 全局作用域使用await的问题
    • form(fieldName)的错误调用方式(改为form[fieldName])
    • classlist的拼写错误(改为classList)
    • document.querySelector("p.error".style.display)的语法错误

内容的提问来源于stack exchange,提问作者RingMaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:54:22