簡體   English   中英

Razor 中的 JavaScript

[英]Javascript inside Razor

我必須在 Razor 中使用 javascript 代碼。 代碼是:

@if (element.ParentItemID == null)
{
    <script type="text/javascript">
        $(window).resize(function () {
            if ($(window).width() > 640) {
                @Html.ActionLink(element.PageTitle, "Details", "Items", new { @parentitem = "website", @url = (element.Url) }, new { @class = "" })
            }
            else {
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">@element.PageTitle</a>
            }
        }); //show syntax error
    </script>
}

沒有 javascript 代碼,它會生成一個菜單。 但是當我使用上面的代碼時,它什么也沒顯示。

我在這里嘗試了解決方案,但在這種情況下它不起作用: Mix Razor and Javascript code

您的 javascript 塊需要與您的 html 分開。 使用當前的實現,瀏覽器將嘗試將 html 解釋為無效的 javascript,並且不會發生任何事情。 嘗試切換元素或換出 href 屬性。

@if (element.ParentItemID == null)
{
    <script type="text/javascript">
        $(window).resize(function ()
        {
            var isWideEnough = $(window).width() > 640;
            $(".isWideEnough").toggle(isWideEnough);
            $(".isNotWideEnough").toggle(!isWideEnough);
        });
    </script>

    @Html.ActionLink(element.PageTitle, "Details", "Items", new { @parentitem = "website", @url = (element.Url) }, new { @class = "isWideEnough" })
    <a href="#" class="dropdown-toggle isNotWideEnough" data-toggle="dropdown">@element.PageTitle</a>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM