0

Using the concept unobtrusive JavaScript, I'm trying, for the first time, to place my JavaScript in a separate file from the HTML. But, no matter what I do, I get an error that the file wasn't found.

This is the actual error in the google chrome console (ctrl-shift-j):

GET http://localhost:14385/Home/TestPage.js 404 (Not Found)

I started with a new MVC 4 app. I created a new test page:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <script src="TestPage.js"></script>
    <title></title>
</head>
<body>
    <div>
        <input id="foo" value="snuh" />
    </div>
</body>
</html>

And I created a new TestPage.js in the same folder:

$(document).ready(function() {

    function dosomething() {
        alert('snuh');
    }

    document.getElementById('foo').onclick = dosomething;
});

I've tried the tips posted here, but I always get an error that the JavaScript file isn't found. Any idea what's wrong with this simple test?

Note: The TestPage actually displays, with the input box showing.

This is the layout in solution explorer:

enter image description here

4

1 回答 1

1

确保使用服务器端助手从正确的位置引用您的 javascript:

<script src="<%= Url.Content("~/TestPage.js") %>"></script>

无论您从哪个位置呈现此视图,这都会正确引用 javascript 文件。它显然假设您已将 javascript 文件放在应用程序的根目录中。约定是为此使用 Scripts 文件夹:

<script src="<%= Url.Content("~/Scripts/TestPage.js") %>"></script>

更新:

现在您已经显示了您的项目结构,您似乎已将TestPage.js文件放在文件~/Views夹中。这行不通。无法从客户端访问此文件夹。它被明确禁止并且不由 IIS 提供。你不应该在里面放置任何静态文件。将您的 javascript 文件夹移动到该~/Scripts文件夹​​。

此外,您似乎在TestPage.js文件中使用了 jQuery,但您从未引用过它,因此您的脚本将无法工作。如果您想使用 jQuery,请确保您也添加了它:

<script src="<%= Url.Content("~/Scripts/jquery-1.8.2.js") %>"></script>
<script src="<%= Url.Content("~/Scripts/TestPage.js") %>"></script>

或者如果您不想使用 jQuery 修复您的脚本,使其不依赖于它:

function dosomething() {
    alert('snuh');
}

window.onload = function() {
    document.getElementById('foo').onclick = dosomething;
};

或者,如果您将脚本放在 DOM 的末尾,您甚至不需要将它们包装在文档就绪处理程序中,因为在此阶段 DOM 将准备好并且您可以对其进行操作:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <div>
        <input id="foo" value="snuh" />
    </div>
    <script src="<%= Url.Content("~/Scripts/TestPage.js") %>"></script>
</body>
</html>

然后在你的脚本中:

function dosomething() {
    alert('snuh');
}
document.getElementById('foo').onclick = dosomething;
于 2013-02-26T16:36:18.507 回答