use*_*949 30 css binding knockout.js
我有一个可观察的数组
var items= [
{"image": "/images/image1.jpg" },
{"image": "/images/image2.jpg" },
{"image": "/images/image3.jpg" }
];
Run Code Online (Sandbox Code Playgroud)
我的模板看起来像这样:
<div data-bind="foreach: items">
<div class="box" data-bind="style: {'background-image': url(image)}"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用.我想要的是这个:
<div>
<div class="box" style="background-image: url(/images/image1.jpg)"></div>
<div class="box" style="background-image: url(/images/image2.jpg)"></div>
<div class="box" style="background-image: url(/images/image3.jpg)"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我怎么能达到这个目的?
SLa*_*aks 63
你需要连接你的字符串:
data-bind="style: { backgroundImage: 'url(\'' + image() + '\')' }"
Run Code Online (Sandbox Code Playgroud)
如果image实际上是一个可观察的,你需要调用它,否则你最终会连接该函数.
请注意,由于您绑定到涉及该属性的表达式,因此必须调用该函数(with ()).否则,您最终会得到一个Javascript表达式来连接函数本身.
您不需要()简单绑定的唯一原因是Knockout检测绑定何时返回属性函数并为您调用它.
我不知道这是好还是坏......
我在我的模型视图中组装了url():
var items= [
{"image": "url(/images/image1.jpg)" },
{"image": "url(/images/image2.jpg)" },
{"image": "url(/images/image3.jpg)" }
];
Run Code Online (Sandbox Code Playgroud)
然后我像往常一样对数据进行数据绑定:
data-bind="style: { 'background-image': image }"
Run Code Online (Sandbox Code Playgroud)