我尝试使用this评分插件但我无法在点击时设置新分数。
我在点击事件上发出ajax请求并获得新的计算得分。我想在click事件中设置新分数。什么是正确的方法?
<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;
}
}
});
答案 0 :(得分: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下,你会发现:
$(&#39;#星&#39;)RATY。(&#39;得分&#39);
获取当前分数。如果没有分数,那么将是未定义的 返回。
$(&#39;#star&#39;)。raty(&#39;得分&#39;,数字);
设定分数。
答案 1 :(得分:4)
答案 2 :(得分: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;
}
}
});