【问题标题】:MVC JS deletethisproduct is not defined at HTMLAnchorElement.onclick (VM457 Index:40)MVC JS deletethisproduct 未在 HTMLAnchorElement.onclick 中定义(VM457 索引:40)
【发布时间】:2020-09-20 09:12:17
【问题描述】:

单击按钮时出现此错误:

deletethisproduct 未在 HTMLAnchorElement.onclick 中定义

我知道使用 onclick 不是最好的主意,但我正在使用它,因为我想从该实例的模型中获取产品 ID 并将其传递给函数

这是我的链接:

<a href="#" class="btn btn-danger" onclick="deletethisproduct(@item.product_id)">Delete </a>

这是js函数:

@section scripts{
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">

    var deletethisproduct = function (productid) {
        $.ajax({
            method: 'POST',
            url: "/Cart/deletecart",
            data: { "id": productid },
            success: function (data) {
                console.log(data);
                //  $("#mymodalBodyDiv").html(data);
            },
            error: function (msg) {
                alert("something wrong" + msg);
            }
        });
    }
</script> 
}

那为什么没有定义呢?还有其他想法可以让我获取此实例的产品 ID 并将其传递给没有 onclick() 的函数吗?

编辑: 我认为 jquery 未被读取或类似的东西我不知道为什么,尽管我在具有相同链接的另一个视图中使用它!

<button class="btn btn-dange mythis">this </button>

我试图简单地从这个按钮发出警报,但什么也没发生,没有警报,控制台中也没有出现错误,它也 没有说“$”没有定义!

$('.mythis').click(function () {
        alert("hiiii")
    }

【问题讨论】:

    标签: javascript jquery ajax asp.net-mvc model-view-controller


    【解决方案1】:

    用 jquery 试试这个

    这种类型的事情使用 jquery 更容易(我认为)。

    链接:

    <a class="btn btn-danger delete" data-id="@item.product_id">Delete </a>
    

    功能:

    @section scripts{
            @Scripts.Render("~/bundles/jquery")
            <script type="text/javascript">
    
                $('.delete').click(function(){
                    var productid = $(this).attr("data-id");
                    $.ajax({
                        method: 'POST',
                        url: "/Cart/deletecart",
                        data: { "id": productid },
                        success: function (data) {
                            console.log(data);
                            //  $("#mymodalBodyDiv").html(data);
                        },
                        error: function (msg) {
                            alert("something wrong" + msg);
                        }
                    });
                });
            </script> 
        }
    

    “data-id”可以是来自 jquery 的访问,使用 .attr https://api.jquery.com/attr/

    【讨论】:

    • 您好,非常感谢您的帮助,这看起来更好,但请您查看 Edit,注意:这是一个部分视图,我想知道 jquery 不能使用部分视图吗?跨度>
    • 是不是因为 jquery 被调用超过 1 次?并尝试添加 $(document)ready(function(){});
    • 问题出在部分视图上,它的 scrtip 代码有问题,所以我将代码放在主视图中,无论如何感谢您的帮助对我有帮助
    • 解决办法可能是把你的js或者jquery逻辑放到另一个js文件里,等你以后调用脚本,有没有检查一下这个->google.com/url?sa=t&source=web&rct=j&url=https://…
    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2019-07-08
    • 2012-12-08
    • 2012-09-18
    • 1970-01-01
    相关资源
    最近更新 更多