Why is my javascript not executed within this Razor code?
I have some working Raphael-js code from this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/an-introduction-to-the-raphael-js-library/ and I'm trying to include the working code in to an MVC3 Razor view. The javascript isn't getting executed. I can't seem to find the error or a good resorce which explains how to include javascript within Razor. Here is my .cshtml where I expect the Rapheael drawing to be rendered at the canvas_container div.
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
</p>
<div id="canvas_container">
</div>
@se开发者_Python百科ction JavaScript
{
<script type="text/javascript" src="@Url.Content("~/Scripts/raphael.js")" />
<script type="text/javascript">
window.onload = function () {
var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
var circle = paper.circle(100, 100, 80);
for (var i = 0; i < 5; i += 1) {
var multiplier = i * 5;
paper.circle(250 + (2 * multiplier), 100 + multiplier, 50 - multiplier)
}
var rectangle = paper.rect(200, 200, 250, 100);
var ellipse = paper.ellipse(200, 400, 100, 50);
}
</script>
}
And here is the rendered view where the javascript is not executed:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
<body>
<div class="page">
<header>
<div id="title">
<h1>MVC Movie App</h1>
</div>
<div id="logindisplay">
[ <a href="/Account/LogOn">Log On</a> ]
</div>
<nav>
<ul id="menu">
<li><a href="/">Home</a></li>
<li><a href="/Home/About">About</a></li>
</ul>
</nav>
</header>
<section id="main">
<h2>Welcome to ASP.NET MVC!</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
</p>
<div id="canvas_container">
</div>
</section>
<footer>
</footer>
</div>
<script type="text/javascript" src="/Scripts/raphael.js" />
<script type="text/javascript">
window.onload = function () {
var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
var circle = paper.circle(100, 100, 80);
for (var i = 0; i < 5; i += 1) {
var multiplier = i * 5;
paper.circle(250 + (2 * multiplier), 100 + multiplier, 50 - multiplier)
}
var rectangle = paper.rect(200, 200, 250, 100);
var ellipse = paper.ellipse(200, 400, 100, 50);
}
</script>
</body>
</html>
Thanks Scott
It's not working because your javascript follows a self-closed script
tag, which is invalid.
You need to change
<script type="text/javascript" src="/Scripts/raphael.js" />
to
<script type="text/javascript" src="/Scripts/raphael.js"></script>
精彩评论