如何将 JavaScript 函数链接到 HTML 锚标记

如何将此 JavaScript 代码链接到 HTML 的锚标记:


<script type="text/javascript">

    $(document).on('click', 'a', function () {

        $.ajax({

            type: 'POST',

            url: '@Url.Action("/brandsOfACategory")',

            contentType: 'application/json; charset:utf-8',

            data: JSON.stringify({ id: this.id })

        })

    });

锚标签:


<a id="@c.Key" href ="???" onclick="???">@c.Key</a>


brandsOfACategory动作方法:


[HttpPost]

    public ActionResult brandsOfACategory(string id)

    {

        var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();

        var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();

        return View(ListOfBrands);

    }

brandsOfACategory.cshtml是:


@model IEnumerable<OnlineStore.Models.Brand>


@{

    Layout = null;

}


<!DOCTYPE html>


<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Brands in a Category</title>

</head>

<body>

    @foreach (var i in Model)

    {


        @i.Name.ToString();

    }

</body>

</html>


蝴蝶不菲
浏览 101回答 2
2回答

梦里花落0921

你可以这样写锚标签-<a id="@c.Key" href ="javascript:void(0);" onclick="postBrands(@c.Key)">@c.Key</a> //replace postBrands with desired function name然后在 javascript 中定义将包含发布请求的函数-function postBrands(key) {&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: '@Url.Action("/brandsOfACategory")',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentType: 'application/json; charset:utf-8',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: JSON.stringify({ id: key })&nbsp; &nbsp; &nbsp; &nbsp; })}

繁花如伊

您可以输入 href 然后href在客户端点击代码中获取:<a id="@c.Key" href ="@Url.Action("actionName","controllerName")">@c.Key</a>在点击事件中,您可以编写以下内容:$(document).on('click', 'a', function () {&nbsp; &nbsp; var Url = $(this).attr("href"); // get href value&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; url: Url, // use it here&nbsp; &nbsp; &nbsp; &nbsp; contentType: 'application/json; charset:utf-8',&nbsp; &nbsp; &nbsp; &nbsp; data: JSON.stringify({ id: this.id })&nbsp; &nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP