我想綁定星級評分使用淘汰賽js和ajax,星級評級是綁定,如果我手動賦值的數據=數據= 3或數據= 4,但我得到的數據從ajax它沒有得到綁定,但我從ajax結果獲得的價值,並將其傳遞給viewmodel它不能在下面工作是我的代碼需要幫助。星級評分綁定使用淘汰賽js
//HTML//
<div id="divstarRating">
<span data-bind="readonlyStarRating:starpoints"></span></a>
</div>
///Custom Binding
ko.bindingHandlers.readonlyStarRating =
{
init: function (element, valueAccessor) {
$(element).addClass("readonlyStarRating");
for (var i = 0; i < 5; i++)
$("<span>").appendTo(element);
$("span", element).each(function (index) {
var observable = valueAccessor();
$(this).hover(
function() { $(this).prevAll().add(this).addClass("hoverChosen") },
function() { $(this).prevAll().add(this).removeClass("hoverChosen") }
)
});
},
update: function (element, valueAccessor) {
var observable = valueAccessor();
$("span", element).each(function (index) {
$(this).toggleClass("chosen", index < observable());
});
}
}
//viewModel
function starRating(data) {
if (data != 0) {
this.starpoints = ko.observable(data);
}
else {
this.starpoints = ko.observable(1);
}
}
ko.applyBindings(new starRating(), document.getElementById('divstarRating'))
//ajax///
$.ajax({
type: "POST",
dataType: "json",
data: xxxx,
url: xxxx+ 'api/xx/xxxxxx',
success: function (data) {
//I am getting the value and passing to viewModel
return new starRating(data);
}
});
//CSS//
.readonlyStarRating span { width:24px; height:24px; background-image: url(../star.png); display:inline-block; cursor: pointer; background-position: -24px 0; }
.readonlyStarRating span.chosen { background-position: 0 0; }
它看起來像你需要先啓動了解[jQuery的Ajax的工作原理(http://api.jquery.com/jquery.ajax/)。 – janmvtrinidad