0

我有一个示例,我正在尝试检测所选元素的文本值并将其填充到弹出窗口中。我知道如何使用 jQuery 做到这一点,但我不想将 Ui 意识带入视图模型。我知道我遗漏了一些简单的东西,但有人可以解释我需要做些什么来绑定 UI 中选择的元素的文本值并将其绑定到 Knockout 中的另一个可观察对象。

完整的工作JsFiddle

减去这里的 CSS 是我迄今为止连接的 html 和 JS

<ul data-bind="foreach: items">
    <li class="divContainer"> <span title="filename" class="tbox" data-bind="text: name, click: $root.openControl "></span>
 <span title="description" class="tbox" data-bind="text: description"></span>

    </li>
</ul>
<div id="nameDiv" class="nameContainer"> <span class="smallTitle"></span>

    <input type="textbox" class="mytextbox" data-bind="value: currentField" />
    <input type="button" id="SaveChange" class="editbtn" value="&#x2714;" />
    <input type="button" id="CancelChange" class="editbtn" value="&#x2716;" />
</div>

JS

var Item = function (name, description) {
    this.name = ko.observable(name);
    this.description = ko.observable(description);
}

    function myViewModel() {
        var self = this;
        //sample list of items
        self.items = ko.observableArray([
        new Item('item 1', ' item 1 Description'),
        new Item('item 2', 'item 2 Description'),
        new Item('item 3', 'Report3 Description'),
        new Item('item 4', 'Report4 Description')]);

        //observable fields
        self.currentField = ko.observable("");

        //bind current item text to field
        self.openControl = function () {
            self.currentField($(this)); ///Here I need to pick up the text of the item that was clicked on
        };
    };

ko.applyBindings(new myViewModel());

function positionDiv(x_pos, y_pos) {

    var d = document.getElementById('nameDiv');
    d.style.display = 'none';
    d.style.position = 'absolute';
    d.style.left = x_pos + 'px';
    d.style.top = y_pos + 'px';
    $('#nameDiv').fadeIn('slow');
}
$('.tbox').click(function () {
    var myText = $(this);
    var t = $(this).attr('title');
    if (t === 'filename') {
        $('.smallTitle').text('Enter new filename');
    } else {
        $('.smallTitle').text('Enter new description');
    }
    displayEditBox(myText);
});


function displayEditBox(myText) {

    //determine middle of span element
    var offset = myText.offset();
    var width = myText.width();
    var height = myText.height();
    var centerX = offset.left + width + 5;
    var centerY = offset.top - 10;

    positionDiv(centerX, centerY);
}

$('#CancelChange').click(function () {
    $('#nameDiv').fadeOut('fast');
    clearField($('.mytextbox'));
});

function clearField(field_name) {
    field_name.val('');
}

提前致谢,

4

1 回答 1

3

更改openControl函数的定义以获取参数:

self.openControl = function (item) {
    self.currentField(item.description());
};

这应该是应用单击item的(数组的元素),因为在进行绑定的位置,数据上下文是绑定的主体。itemsclickforeach: items

于 2013-08-28T19:49:43.150 回答