按钮onclick失效报错:Uncaught ReferenceError: showDiv未定义
解决Uncaught ReferenceError: showDiv is not defined错误
问题原因
你的登录按钮和弹窗HTML通过<partial name="Login">放在了<body>最开头,而定义showDiv()函数的脚本是通过@section Scripts渲染在页面底部(</body>标签前)。这就导致按钮加载完成时,函数还未被定义,点击自然会触发未定义错误。
解决方案
方案1:将函数定义移到登录Partial的HTML之后
直接在Login partial的末尾添加脚本,确保函数在按钮之后定义:
<button onclick="showDiv()">Login</button> <div id="login-popup"> <div id="login-popup-content"> <h2>Login</h2> <form asp-action="Login"> <div class="form-group"> <input asp-for="@Model.LoginVM.Username" placeholder="Username" required /> <span asp-validation-for="@Model.LoginVM.Username"></span> </div> <div class="form-group"> <input asp-for="@Model.LoginVM.Password" placeholder="Password" required /> <span asp-validation-for="@Model.LoginVM.Password"></span> </div> <div class="form-group"> <input type="submit" value="Login" /> </div> </form> </div> </div> <script> function showDiv() { console.log("pressed"); document.getElementById("login-popup").style.display = "flex"; } </script>
同时移除@section Scripts里的这段函数代码。
方案2:使用DOM加载完成事件绑定点击事件(推荐,避免全局函数污染)
保留@section Scripts里的代码,修改为DOM加载完成后绑定事件,同时去掉按钮上的onclick属性:
修改HTML按钮:
<button id="login-btn">Login</button>
修改脚本:
@section Scripts { <script> // 原生JS方式 document.addEventListener('DOMContentLoaded', function() { document.getElementById('login-btn').addEventListener('click', function() { console.log("pressed"); document.getElementById("login-popup").style.display = "flex"; }); }); // 或者用jQuery(页面已加载jQuery) // $(document).ready(function() { // $('#login-btn').click(function() { // console.log("pressed"); // $("#login-popup").css('display', 'flex'); // }); // }); </script> @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } }
方案3:将脚本移到布局的<head>中
在布局的<head>标签内添加脚本,但需加上DOMContentLoaded监听,避免DOM未加载就执行脚本:
<head> <!-- 其他头部资源 --> <script> function showDiv() { console.log("pressed"); const popup = document.getElementById("login-popup"); if(popup) popup.style.display = "flex"; } </script> </head>
注:此方式不推荐,会阻塞页面渲染,且依赖元素加载顺序。
额外优化建议
- 表单内多个
<div>使用了重复的id="form-group",ID必须唯一,建议改为class="form-group",与现有CSS选择器#login-popup-content .form-group匹配。
内容的提问来源于stack exchange,提问作者dev-113
相关产品推荐
相关产品推荐

