我有一个示例我试图检测所选元素的文本值,并在弹出窗口中填充它。我知道如何使用jQuery做到这一点,但我不想将Ui意识带入viewmodel。我知道我错过了一些简单的东西,但有人可以解释我需要做什么来绑定UI中选择的元素的文本值,并将其绑定到Knockout中的另一个observable。
正常工作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="✔" />
<input type="button" id="CancelChange" class="editbtn" value="✖" />
</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('');
}
提前致谢,
答案 0 :(得分:3)
更改openControl
函数的定义以获取参数:
self.openControl = function (item) {
self.currentField(item.description());
};
这应该是应用了点击的item
(items
数组的一个元素),因为在click
绑定的位置,数据上下文是foreach: items
绑定的主体。