简体   繁体   中英

jQuery doesn't work with ASP.NET MVC

I'm learning MVC and I am trying to use jQuery. This is my code:

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript">    
    </script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"  type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>   
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script> 
</head>

<body>
    @RenderBody()
</body>
</html>

Index.cshtml

@{
    ViewBag.Title = "Index";
}
<script src="@Url.Content("~/Scripts/JScript1.js")" type="text/javascript"></script>

<h2 id="ind">Index</h2>

<div id="picture">

</div>

and JScript1.js

$(document).ready(function () {
    alert("Test alert");
    $("#picture div").css("background-color", "red");
});

Alert shows fine but color doesn't change. Nothing with jQuery doesn't work. I have also tried:

document.body.style.backgroundColor = "red";

but this also doesn't work.

What's the problem here it should be very simple???

Use

$(document).ready(function () {
    alert("Test alert");
    $("div #picture").css("background-color", "red");
});

In your code, you use: #picture div , and the script tries to set color to div which is NESTED in the element with id = picture . You should use $("div #picture") , or even shorter (as each id has to be unique) : $("#picture") .

Change your code to

$(document).ready(function () {
    alert("Test alert");
    $("div#picture").css("background-color", "red");
});

Or better to use

$(document).ready(function () {
        alert("Test alert");
        $("#picture").css("background-color", "red");
    });

I used

<div id="picture">
  TEST
</div>

and

$(document).ready(function () {
  alert("Test alert");
  $("#picture").css("background-color", "red");
});

Without something in the div it doesn't show. also here could be something in Site.css that is messing with this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM