2

我正在尝试使用评分插件,但无法在点击时设置新分数。

我正在对点击事件发出 ajax 请求并获得新的计算分数。我想在点击事件中设置新分数。正确的方法是什么?

<div class="rating" data-id="some-int" data-score="0.5"></div>

Javascript:

$(".rating").raty({
    score: function () { return $(this).attr("data-score"); },
    click: function (score, evt) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "./ajax.asmx/RateImage",
            data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
            dataType: "json",
            async: false,
            success: function (result) { actionResult = result.d; }
        });

        if (actionResult.Success) {
            console.log("Score: " + actionResult.Message);
            score = actionResult.Message;
        } else { // cancel rating
            alert(actionResult.Message);
            return false;
        }
    }
});
4

3 回答 3

5

有一个内置的方法来设置新的分数,所以只需使用:

$('.rating').each(function(i) {
    var thisRating = $(this);
    thisRating.raty({
        score: function () {
            return $(this).data('score');
        },
        click: function (score, evt) {
            $.ajax({
                type: 'post',
                contentType: 'application/json; charset=utf-8',
                url: './ajax.asmx/RateImage',
                data: {
                    ImgId: thisRating.data('id'),
                    Score: score
                },
                dataType: "json",
                success: function (result) {
                    thisRating.raty('score', result.d.Message);
                }
            });
            return false;
        }
    });
});

docs - Functions下,您会发现:

$('#star').raty('score');

获取当前分数。如果没有分数,则返回 undefined。

$('#star').raty('score', number);

设定分数。

于 2015-06-25T08:38:58.157 回答
4

你可以做

$(".rating").raty('setScore', score);

看到它工作

http://codepen.io/anon/pen/qdVQyO

于 2015-06-25T08:39:08.917 回答
2

根据文档,您可以简单$('#selector').raty({score: 3})地设置分数。所以在回调中,你可以$(".rating").raty({score: actionResult.Message})这样调用:

$(".rating").raty({
    score: function () { return $(this).attr("data-score"); },
    click: function (score, evt) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "./ajax.asmx/RateImage",
            data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
            dataType: "json",
            async: false,
            success: function (result) { actionResult = result.d; }
        });

        if (actionResult.Success) {
            console.log("Score: " + actionResult.Message);
            $(".rating").raty({score: actionResult.Message});
        } else { // cancel rating
            alert(actionResult.Message);
            return false;
        }
    }
});
于 2015-06-23T06:06:13.653 回答