在<a> in cshtml not working

时间:2018-06-28 22:07:20

标签: javascript jquery razor asp.net-mvc-5

I would like to toggle a sub-list (hidden/visible) upon clicking on an tag but nothing is toggling.

Using MVC 5 framework.

Here's my cshtml page:

@section Scripts
{
    <script >
        $('a').click(function () {
            $('#myElement').toggle(function () {
                if ($(this).css('display') === 'none') {
                    $(this).prop('hidden', 'hidden');
                }
                else {
                    $(this).removeProp('hidden');
                }
            })
        })
    </script>
}

<ul id="menu">
    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    <li><a href="#">Materials</a>
    <ul id="myElement">
        <li>something</li>
    </ul>
    </li>
   </ul>

I would like to click on Materials and show/hide the "myElement" unordered list below it.

Anybody see what I'm doing wrong?

I moved the script to below the html and added a document ready...no luck.

@section Scripts
{
    <script>
        $(document).ready(function () {
        $('a').click(function () {
            $('#myElement').toggle(function () {
                if ($(this).css('display') === 'none') {
                    $(this).prop('hidden', 'hidden');
                }
                else {
                    $(this).removeProp('hidden');
                }
            })
            })
        })
    </script>
}

Here is my default _Layout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Procurement</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div id="header"  class="navbar-fixed-top">
        <table width="100%" cellspacing="10">
               <tr>
                <td width="10%"><img src="../../Images/Logo.PNG" /></td>
                <td><h3 style="vertical-align: central; font-family:Verdana; color: darkslategray">Procurement System</h3></td>
            </tr>
            <tr>
                <td colspan="2"><hr style="height:10px; width:100%; background-color:teal" /></td>
            </tr>
        </table>
        <div id="menuContainer">
            @Html.Action("Menu", "Layout", "Layout")
        </div>

        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p>&copy; @DateTime.Now.Year - Procurement Application</p>
            </footer>
        </div>
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

0 个答案:

没有答案