Javascript 单击更改图像src绑定
单击不同的图像后,我想更改Javascript 单击更改图像src绑定,javascript,html,data-binding,knockout.js,Javascript,Html,Data Binding,Knockout.js,单击不同的图像后,我想更改img的attr:{src:…}绑定,请参见以下示例: $(document).ready(function () { var viewModel = { list: ko.observableArray(), showRenderTimes: false }; ko.applyBindings(viewModel); window.vm = vi
img
的attr:{src:…}
绑定,请参见以下示例:
$(document).ready(function () {
var viewModel = {
list: ko.observableArray(),
showRenderTimes: false
};
ko.applyBindings(viewModel);
window.vm = viewModel;
});
$.ajax({
type: "POST",
url: "WebService.asmx/GetList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var c= msg.d;
vm.list(c);
},
failure: function (msg) {
alert(msg.d);
}
});
使用此html:
我想在单击其他图像时更改src
的图片绑定。例如,如果我单击“pic1”,我希望“mainpic”获得图像src
“Picture2”和“pic1”获得图像src
“Picture1”
不用说,我每次点击“其他图片”都需要它。如下所示 HTML
<div class="Container">
<!-- ko if: selectedPicture() -->
<div class="MainPicture" data-bind='with: selectedPicture'>
<img id="mainpic" class="MainPic" src="#" data-bind="attr: { src: imageUrl }" />
</div>
<!-- /ko -->
<ul class="OtherPicture" data-bind="foreach: list">
<li>
<img class="SubPic" src="#" data-bind="attr: { src: imageUrl}, click: $parent.selectPicture" />
</li>
</ul>
</div>
嗨,谢谢你的评论。我只是想知道如何连接这两个视图模型我不完全确定“连接”是什么意思。
var Picture = function (data) {
var self = this;
self.id = ko.observable(data.id || 0);
self.name = ko.observable(data.name || '');
self.imageUrl = ko.observable(data.imageUrl || '');
return self;
};
var ViewModel = function () {
var self = this;
self.selectedPicture = ko.observable(new Picture({
id: 4,
name: 'Picture 4',
imageUrl: 'http://placehold.it/100x100'
}));
self.list = ko.observableArray([new Picture({
id: 1,
name: 'Picture 1',
imageUrl: 'http://placehold.it/150x150'
}), new Picture({
id: 2,
name: 'Picture 2',
imageUrl: 'http://placehold.it/260x260'
}), new Picture({
id: 3,
name: 'Picture 3',
imageUrl: 'http://placehold.it/370x370'
})]);
self.selectPicture = function (item) {
self.selectedPicture(item);
};
return self;
};
var vm = new ViewModel();
ko.applyBindings(vm);
window.vm = vm;