我尝试调用 attr src 上的函数但失败。这是我尝试过的。
function FavoriteViewModel() {
var self = this
self.FavoriteProfiles = ko.observableArray([])
self.getRating = function(Rating){
//here i want conditions and concat image path
return does nothing here
}
self.LoadData = function(){
//run ajax and put its result in self.FavoriteProfiles
self.FavoriteProfiles(Result)
}
self.LoadData()
}
当我运行 ajax 时,会产生这样的结果。结果有多个,我只发布单个对象来理解
ProfileId 20
Age 21
Gender "F"
Rating 4
我像这样绑定(bind)数据
<div id="favorite-related-profiles" data-bind="foreach:FavoriteProfiles">
<article class="prfl_box">
<p>
<span id="favorite-related-age" data-bind="text:Age"></span>
<span id="favorite-related-gender" data-bind="text:Gender"></span>
<br>
<img id="favorite-related-rating" class="pro_rating" src="" data-bind="attr:{src:Rating}">
</p>
</article>
</div>
当我尝试这样的绑定(bind)时
<img id="favorite-related-rating" class="pro_rating" src="" data-bind="attr:{src:$root.getRating.bind($data,Rating)}">
我在 src 中得到了这个
src="function () { [native code] }"
如何动态生成 src 属性。
注意我需要显示图像。图像命名为 4Rating.png 、 5Rating.png 、 default.png。
我想检查 src 属性中的 rating 是否为 4 assing 4 rating。我怎样才能做到这一点。
最佳答案
好吧,他们的方法很少。现在,如果我理解了您的问题,那么您需要将 src 属性设置为 4 rating.png
、 5 rating.png
等,具体取决于评级值为 4,5分别。
如果是这种情况,请查看此 DEMO - A dirty way
现在,让我们让它按照您的代码运行:-
您可以查看DEMO2- Proper way 。如果您检查元素并看到 yopu,您会发现 HTML 标记如下:-
<td data-bind="attr:{src: $root.getRating($data)}" src="4rating.png">
</td>
希望有帮助。
编辑:-
只是一个建议,当您使用 Knockout 模型时,您可以将模型分开。保持流程简单,它会更具可扩展性。 我将分享如何使用 Revealing Module Pattern DEMO 学习通过 knockout 进行编码。
创建 View 模型就像这样简单:-
function FavoriteViewModel(data) {
var self = this
self.ProfileId = data.ProfileId;//Do some exception handling
self.Age = data.Age;//Do some exception handling
self.Gender = data.Gender;//Do some exception handling
self.Rating = data.Rating;//Do some exception handling
self.RatingExtended = data.Rating + "rating.png"; //Some random stuff
}
创建一个变量来保存您最喜爱的数组,并将数据绑定(bind)
到 HTML。
var FavoriteProfiles = ko.observableArray([]);
最后,AJAX 调用获取数据并将其分配给您的 FavouriteProfiles
。
var ajaxdata = DummyAjaxCall(); //get all profiles
$.each(ajaxdata, function (index, value) {
FavoriteProfiles.push(new FavoriteViewModel(value)); //Create a Model
});
关于javascript - 在knockout.js中动态调用attr src上child的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312822/