有条件地在淘汰表中添加一个元素属性 [英] Conditionally add an element attribute in knockout.js

查看:58
本文介绍了有条件地在淘汰表中添加一个元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

knockout.js库具有 "attr"数据绑定,您可以动态更改HTML元素属性的值(例如"title").但是,在某些情况下,取决于绑定对象上的相应可观察对象,可能需要或可能不需要该属性.例如,如果我的模型具有可观察到的标题",那么我可能想设置标题"属性(如果存在)(非空),或者完全跳过该属性(如果不存在)(空).

The knockout.js library has an "attr" data binding which allows you to dynamically change the value of an HTML element attribute (e.g. the "title"). However, in some cases, the attribute may or may not be needed depending on the corresponding observable on the bound object. For example, if my model has a "title" observable I might want to set the "title" attribute if it is present (non-null) or skip the attribute entirely if it is not present (null).

敲除是否提供有条件地设置属性的任何方式? (理想情况下,无需有条件地渲染整个元素开始标记...)

Does knockout provide any way to conditionally set an attribute? (Ideally without conditionally rendering the entire element opening tag...)

[注意] 这个类似命名的问题实际上是由淘汰赛对CSS类的特殊处理解决的,并且与该问题(或其标题)无关:

[Note] This similarly named question was actually resolved by knockout's special handling of CSS classes and does not relate to this question (or its own title): How to conditionally render an css class with knockoutjs

推荐答案

选择(我是手动生成而不是内置的剔除)时,我需要这样做.

I needed this when selecting an (that I was generating manually instead of built-in knockout).

<option 
 data-bind="text: text, 
    attr:{
     value:value,
     'selected': typeof(selected) !== 'undefined' ? selected : null 
     }">
 Choice X
</option>

这表示始终更新文本"属性并添加值"属性,但仅在数据已经定义了选定"值时才添加选定".

This says to always update the 'text' attribute and to add the 'value' attribute, but only add 'selected' if the the data already has a value of 'selected' defined.

这篇关于有条件地在淘汰表中添加一个元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆