1

JavaScript is enabled in the Chrome browser. I want an alert to appear when a paragraph is clicked. WHY is it not working?! If I had got the JavaScript working I assume the jQuery would also work.

Here is the _Layout.cshtml page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/Scripts/jquery-1.7.1.js")
    @Scripts.Render("~/bundles/modernizr")

    <script>
        $(document).ready(
            $("#para").click(function() {
                alert("you clicked the paragraph");
            })
        );
    </script>
</head>
<body>
    <p id="para">Some paragraph</p>

 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</body>
</html>
4

2 回答 2

5

You have included jquery twice. Once in the head section and once at the end. Try like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <p id="para">Some paragraph</p>

    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript">
        $("#para").click(function() {
            alert("you clicked the paragraph");
        });
    </script>
    @RenderSection("scripts", required: false)
</body>
</html>

The @Scripts.Render("~/bundles/jquery") call uses ASP.NET MVC 4 new bundling mechanism which is including jQuery. Look at your ~/App_Start/BundleConfig.cs file to see how this is configured. Also notice how in my example I have removed the document.ready call because it is no longer necessary since I have placed the script at the end of the document.

于 2013-03-30T18:20:50.847 回答
3
$(document).ready(
        $("#para").click(function() {
            alert("you clicked the paragraph");
        })
    );

Should be:

$(document).ready(function(){
//                ^^^^^^^^^^^  <<<<--------------------------------
    $("#para").click(function() {
        alert("you clicked the paragraph");
    });
});
于 2013-03-30T18:20:36.287 回答