1

我已经实现了 jquery 星级评分。当用户添加其评分时,我将其保存到数据库并禁用星级评分。
但是在禁用用户再次单击星号后,它会再次调用 js 函数并尝试将分数保存到数据库。

<input name="rating" type="radio" class="star" value="3" />
...
$('.star').click(function(event) {
        $.ajax({
                type: "POST",
                url: '@Url.Action("Rate", "Rating")',
                data: $("#rate").serialize(),
                success: function(response) {
                    alert('Your rating has been recorded');   
                    $('.star').rating('disable', true);
                },
                error: function(response) {
                alert('There was an error.');
              }
            });
        });
4

1 回答 1

4

off()您可以在 ajax 调用之后取消绑定点击事件(使用)

 $('.star').click(function(event) {
     var $this = $(this);
     ...
     success: function(response) {
         alert('Your rating has been recorded');   
         $this.off('click');
     },

 });

我想你可能有几个.star元素,所以你应该只解除附加在点击链接上的处理程序。

另一种更简单的可能性是使用 绑定处理程序.one(),就像这样

 $('.star').one('click', function(event) {
     var $this = $(this);
     ...
     success: function(response) {
         alert('Your rating has been recorded');   

     },

 });

这将只允许每个不同.star元素的单击事件

无论如何,我强烈建议您在服务器端也进行这种检查。不要依赖客户端进行可能更改服务器上数据的操作

于 2012-09-03T16:24:47.423 回答