本文介绍了Knockout.js:有条件绑定div的title属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一个视图模型,其中包含一些设备当前状态概览的数据.到目前为止,一切都很好,除了一个问题:我需要根据我的 viewModel 中的另一个值设置 div 元素的 title 属性.

I have a viewModel on my page that holds the data for an overview of current states of some devices. So far everything works great except for one issue: I need to set the title attribute of a div element depending on another value in my viewModel.

我知道你基本上可以这样设置title属性(在div标签的data-bind属性内):

I know that you can basically set the title attribute like this (within the data-bind attribute of the div tag):

attr: { title: 'Some title' }

使用上面的语句,当悬停 div 时,Some title"被设置为工具提示.我也可以设置:

Using the statement above, "Some title" gets set as tooltip when hovering the div.I can also set this:

attr: { title: ConnectState.Value() }

并且它输出我当前 viewModel 数据的正确值(一个整数值),因此 viewModel 被正确填充.

and it outputs the correct value (an integer value) of my current viewModel data, so the viewModel gets populated correctly.

现在我需要把它改成这样:

Now I need to change this to something like that:

attr: {
  title: {
    'Text 1': ConnectState.Value() == 0,
    'Text 2': ConnectState.Value() == 1,
    'Text 3': ConnectState.Value() == 2,
    'Text 4': ConnectState.Value() == 3
  }
}

上面的例子只会给出[object Object]"作为标题(或者作为工具提示).我该如何解决?非常感谢提前!

The example above will only give "[object Object]" as title (resp. as tooltip). How can I fix that?Thanks a lot in advance!

推荐答案

在您的视图模型中定义一个 ko.computed.

Define a ko.computed in your viewmodel.

self.ConnectTitle = ko.computed(function() {
   return 'Text ' + (self.ConnectState.Value() + 1).toString();
});

那么:-

attr: { title: ConnectTitle }

作为您的绑定.如果您的文本只是一个简单示例,您可以将计算函数的内容替换为适合您需要的内容.

As your binding. You can replace the contents of the computed's function with something that'll suit your needs, if your text was just a simple example.

这篇关于Knockout.js:有条件绑定div的title属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 17:19
查看更多