单击时更改图像src绑定

时间:2014-12-08 19:24:37

标签: javascript html5 data-binding knockout.js

我想在点击其他图片后更改img的{​​{1}}绑定,例如:

attr: { src: ...}

使用这个html:

    $(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);
        }
    });

我希望在点击其他图片时更改<div class="Container" data-bind="foreach: list"> <div class="MainPicture"> <img id="mainpic" class="MainPic" src="#" data-bind="attr: { src: Picture1 }" /> </div> <div class="OtherPicture"> <img id="pic1" class="SubPic" src="#" data-bind="attr: { src: Picture2}" /> <img id="pic2" class="SubPic" src="#" data-bind="attr: { src: Picture3 }" /> <img id="pic3" class="SubPic" src="#" data-bind="attr: { src: Picture4 }" /> </div> </div> 的图片装订。例如,如果我点击&#34; pic1&#34;我想要&#34; mainpic&#34;获取图像src&#34;图片2&#34;和&#34; pic1&#34;获取&#34; Picture1&#34;。

的图像src

毋庸置疑,我需要为每个&#34; OtherPicture&#34;我点击了。

1 个答案:

答案 0 :(得分:1)

类似以下内容。 JSFiddle Demo

<强> 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>

JS

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;