【发布时间】:2017-03-02 07:55:43
【问题描述】:
下面是我在 C# MVC 5 中的代码。我制作了一个名为 _ClockPartial.cshtml 的局部视图,它是一个简单的秒表,我使用“@Html.Partial("_ClockPartial")”将其放入主页 Index.cshtml .
我的问题是如何将 javascript 分离到脚本文件夹 (~/Scripts/clocker.js) 中但仍然可以正常运行?当我尝试自己将其分开时,我还没有让它正常工作。我听说你不能在部分视图中这样做,但我不知道为什么。即使我不能部分执行它,我仍然想知道如何将 javascript 分离到它自己的文件中并在我的 .cshtml 视图之一中调用它。提前感谢您的帮助!
第一个文件是我的 Index.cshtml
@{
ViewBag.Title = "Home Page";
}
@using Microsoft.AspNet.Identity
@Scripts.Render("~/bundles/jquery")
<div class="jumbotron">
<h1>Clocker</h1>
<p class="lead">Welcome to clocker! Please sign in to start clocking your hours! Don't do too little or your hard earned cash goes into the punishiment piggy bank!</p>
@if (Request.IsAuthenticated)
{
@Html.Partial("_ClockPartial")
}
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
这是 _ClockPartial.cshtml
@Scripts.Render("~/bundles/jquery")
<h2><time>03:00:00</time></h2>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
<script type="text/javascript">
$(document).ready(function () {
var h1 = document.getElementsByTagName('h2')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 3,
isRunning = false,
t;
/* increments timer */
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
/* decrements timer */
function subtract() {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 59;
hours--;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(subtract, 1000);
}
/* enable following line to start timer automatically */
//timer();
/* Start button */
start.onclick = function () {
if (!isRunning) {
timer();
isRunning = true;
}
}
/* Stop button */
stop.onclick = function () {
clearTimeout(t);
isRunning = false;
}
/* Clear button */
clear.onclick = function () {
h1.textContent = "03:00:00";
seconds = 0; minutes = 0; hours = 3;
isRunning = false;
}
});
</script>
<p></p>
【问题讨论】:
-
首先,如果它在 index.cshtml 中,则不需要在局部视图中包含 jquery。然后将所有脚本放在不同的文件中,并在局部视图中包含该文件的引用。这应该会让你继续前进
-
@NirbhayJha 我尝试过这样做,要么是我的语法不正确,要么是因为我之后没有任何功能。
标签: javascript c# asp.net-mvc