简体   繁体   English

如何在 ASP.NET Core MVC razor 视图中使用脚本标签

[英]How to use script tag in an ASP.NET Core MVC razor view

I want to use javascript in a razor view in the MVC project.我想在 MVC 项目的 razor 视图中使用 javascript。 I want to show a message to the user by clicking the post button.我想通过单击发布按钮向用户显示一条消息。 I put the script tag in Section below the page but on hitting F12 it shows 'btn' is null .我将脚本标记放在页面下方的Section中,但在按 F12 时显示'btn' is null I'm testing my project on IISExpress in Firefox我正在 Firefox 中的 IISExpress 上测试我的项目

<form method="post">
--------a few input fields in a form-------
 <button id="button" type="submit" class="btn btn-lg btn-success">send</button>
</form>
<div class="submit-progress d-none">
    <label>be patient please...</label>
</div>
@section scripts{
    <partial name="_ValidationScriptsPartial" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.2.7/js/fileinput.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            const btn = document.getElementById("#button");
            btn.addEventListener("click", function () {
                $(btn).prop("disabled", true);
                $(".submit-progress").removeClass("d-none");
            })
        });
    </script>
}

When using getElementById you only need to pass the name not the selector #使用 getElementById 时,您只需要传递名称而不是选择器#

const btn = document.getElementById("button");

You have used the scripts section correctly.您已正确使用脚本部分。

There are multiple problems with your code mostly from mixing jQuery and native JavaScript methods.您的代码存在多个问题,主要是由于混合了 jQuery 和本机 JavaScript 方法。 You can make it work by fixing the 3 lines shown to use jQuery. Note that "this" refers to the element to which the event handler is attached, in this case the button.您可以通过修复显示的 3 行以使用 jQuery 来使其工作。请注意,“this”指的是事件处理程序附加到的元素,在本例中是按钮。

$(document).ready(function() {
  // const btn = document.getElementById("#button"); <-- REMOVE
  $("#button").click(function() { // <-- CHANGE
    $(this).prop("disabled", true); // <-- CHANGE
    $(".submit-progress").removeClass("d-none");
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM