简体   繁体   English

如何调用此JS函数并传递参数?

[英]How do I call this JS function and pass a parameter through?

I have the following script for my SignalR hub and I'm having trouble on calling my function so that I can pass a parameter through. 我的SignalR集线器具有以下脚本,并且在调用函数时遇到麻烦,因此无法传递参数。

$(function () {
    var hub = $.connection.commentsHub;

    $.connection.hub.start().done(function () {
        function deleteComment(commentId) {
            hub.server.DeleteComment(commentId);
        }
    });
});

And then in my list of comments I am trying to call my deleteComment function with this but I get an error stating that deleteComment is not defined. 然后在我的注释列表中,我试图以此调用我的deleteComment函数,但出现错误,指出未定义deleteComment。

<a onclick="deleteComment(@item.CommentId)">Delete</a>

How do I call my deleteComment function? 如何调用我的deleteComment函数?

Or, is there a better way to pass the parameter to my server? 还是有更好的方法将参数传递给我的服务器?

Your deleteComment() function is buried within two layers of other functions, so there's no way your inline JavaScript can access it. 您的deleteComment()函数隐藏在其他函数的两层中,因此内联JavaScript无法访问它。 I suggest (1) taking it out of your done callback because there's no reason for it to be there and (2) using unobtrusive JavaScript for this: 我建议(1)从done回调中删除它,因为没有理由将其放在其中,以及(2)为此使用不引人注目的JavaScript:

HTML: HTML:

<a href="#" class="delete-comment" data-commentid="@item.CommentId">Delete</a>

JavaScript: JavaScript的:

$(function () {
    var hub = $.connection.commentsHub;

    function deleteComment(commentId) {
        hub.server.DeleteComment(commentId);
    }

    $.connection.hub.start().done(function () {
        $(".delete-comment").click(function() {
            deleteComment($(this).attr("data-commentid"));
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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