문제

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.

$(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.

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

How do I call my deleteComment function?

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. 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:

HTML:

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

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top