如何在ASP.NET Core中使用jquery [英] How to use jquery in ASP.​NET Core

查看:698
本文介绍了如何在ASP.NET Core中使用jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个ASP.NET核心模板并编写了一个jquery脚本.当我查看该页面时,我看到该页面已加载了jquery,但脚本未运行.我查看了ASP.NET文档页面,并且layout.cshtml看起来相同,因此是否必须采取其他步骤才能使jquery正常工作? 主页

I created a ASP.NET core template and wrote a jquery script. When I look at the page I see that jquery is loaded into the page, but the script doesn’t run. I looked at the ASP.NET docs page and my layout.cshtml looks the same, so are there extra steps I must take to get jquery working? Home page

@{
    ViewData["Title"] = "Home Page";
}
<!-- Page Content-->
<div class="container">
    <div class="row">
        <form method="post" enctype="multipart/form-data">
            <input type="file" id="files" name="files" multiple />
            <input type="button" id="upload" value="Upload Selected Files" />
        </form>
    </div>
</div>
<script>
    $(document).ready(function () {
        alert("Test"); 
    });
</script>

解决方案

@section scripts
{
    <script>
        $(document).ready(function() {
            alert("Test");
        });
    </script>
}

推荐答案

我怀疑您的jquery在页面其余内容之后加载.

I suspect your jquery is loaded after the rest of the page content.

这意味着您不能引用jquery对象,因为该库尚未初始化.

This means that you cannot reference jquery objects as the library has not been initialised yet.

在加载jquery之后移动页面脚本.

Move the page script after jquery has loaded.

<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
  $(document).ready(function () {
    alert("Test"); 
  });
</script>

为了提高效率,我建议您采用以下两种方式之一进行操作:

For efficiency I recommend you do this in one of two ways:

选项1

使用在jquery之后加载的主脚本文件.

Use a master script file that loads after jquery.

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/master.js"></script>


选项2

使用占位符模板,该模板将始终在jquery之后加载,但可以在各个页面上初始化.

Use a placeholder template that will always load after jquery but can be initialised on individual pages.

母版版式页面

<script src="~/lib/jquery/dist/jquery.js""></script>
@RenderSection("Scripts", required: false)

内容页面

@section Scripts {
  <script>
    $(function () {
      alert("Test"); 
    });
  </script>
}

这篇关于如何在ASP.NET Core中使用jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆