JS文件不会链接到ASP.NET MVC视图 [英] JS files are not linking to asp.net MVC view

查看:303
本文介绍了JS文件不会链接到ASP.NET MVC视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个asp.net MVC应用程序。

I am creating an asp.net MVC application.

我有一个命名视图接收,并放置在查看/主文件夹中。

I have a view named "receive" and it placed in Views/Main folder.

我想补充js文件。

在智能感知,我正在访问js文件的功能。

In intellisense, I am getting access to js file functions.

但是当我运行应用程序时,js文件是不是链接。

But when I run the application, the js file is not linking.

我的观点是如下

 @model dSite.Models.MModels
 <script type="text/javascript" src="../../Scripts/Jquery-2.1.js">        </script>
 <script>         
   $("#btn").click(function () 
       { alert("aa"); 
    });

</script>
@{
     ViewBag.Title = "receive";
 }
<h2>
receive</h2>
<input type="text" id="txtname" placeholder="enter name" />
<input type="button" id="btn" value="click here" /> 

和我的脚本文件夹在根目录下。

And my Scripts folder is at the root.

我如何我的js文件链接到我的看法?我已经试过了,但上面它不工作

How can I link my js file to my view? I have tried the above but it's not working

以下是文件结构

.js文件结构

推荐答案

首先,jQuery是加载!你会看到一个 $没有定义错误在浏览器控制台,如果它不是。

Firstly jquery is being loaded! You would have seen a $ is not defined error in the browser console if it wasn't.

真正的问题是,你有以下脚本在页面的顶部,但里面没有的document.ready。

The real problem was that you have the following script at the top of the page but not inside document.ready.

<script>         
    $("#btn").click(function () { 
        alert("aa"); 
    });
</script>

什么情况是作为视图呈现,脚本的第一行试图附加。点击()事件元素与 ID =BTN,但在这一点上的元素不会在DOM存在(其进一步下跌的页面),因此您实际事件连接到一个未定义的元素(一个不存在的)。

What happens is as the view is rendered, the first line of the script is trying to attach a .click() event to the element with id="btn", but at this point that element does not exist in the DOM (its further down the page) so the you actually attaching the event to an undefined element (one that does not exist).

除非你马上把你的脚本结束&LT之前; / BODY&GT; 标签,你应该总是包装你的脚本的 $(文件)。就绪()

Unless you place your scripts immediately before the closing </body> tag, you should always wrap your scripts in $( document ).ready()

这篇关于JS文件不会链接到ASP.NET MVC视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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