鼠标悬停时,如何将文本绑定到元素?
我到目前为止的Javascript:
self.books = ko.observable();
self.leftBooks = self.books() - self.allBooks();
对应观点:
<button data-bind="text: books"></button>
当鼠标悬停在按钮上时,我想显示leftBooks
变量。当鼠标悬停时,我想显示books
变量。
答案 0 :(得分:1)
使用event
绑定:
HTML:
<button data-bind="text: booksTitle, event: {mouseover: mouseOver, mouseout: mouseOut}"></button>
JS:
function ViewModel() {
var self = this;
self.books = ko.observable(10);
self.allBooks = ko.observable(100);
self.leftBooks = self.books() - self.allBooks();
self.booksTitle = ko.observable(10);
self.mouseOver = function () {
self.booksTitle(self.leftBooks);
}
self.mouseOut = function () {
self.booksTitle(self.books());
}
}
答案 1 :(得分:1)
你走了:
我做了什么:
代码:
self.allBooks = ko.observable(50);
self.books = ko.observable(10);
self.leftBooks = ko.computed(function () {
return self.allBooks() - self.books();
});
self.showLeftBooks = ko.observable(false);
self.buttonText = ko.computed(function () {
return self.showLeftBooks() ? self.leftBooks() : self.books();
});
self.mouseOver = function () {
self.showLeftBooks(true);
}
self.mouseOut = function () {
self.showLeftBooks(false);
}
编辑:亚历山大对他的回答的更新几乎完全相同,但有一个属性更少。在我看来,你是否想要引入额外的opbservable'showLeftBooks'是一个品味问题。我觉得它使代码的意图更加清晰,但如果你愿意,你可以完全省略它。