【问题标题】:Dynamic attr in textbox data-bind knockout JS文本框数据绑定淘汰 JS 中的动态属性
【发布时间】:2016-10-21 17:50:43
【问题描述】:

我需要在文本框数据绑定中添加动态属性

<input class="form-control" type="text" data-bind="
  attr:{
    name:$data.FieldName, 
    req: !$data.Nullable, 
    placeholder:$data.DefValue, 
    disabled:$data.Editable != null && !$data.Editable == true, 
    required: $data.Nullable != null && !$data.Nullable, 
    'data-bv-notempty':$data['data-bv-notempty'], 
    'data-bv-notempty-message': $data['data-bv-notempty-message']
  }, 
  value: $root.selScreen.isEditMode() ? ActualData : ''
">

如果我在列表下面的数组中定义,那么它应该添加

'data-bv-notempty': $data['data-bv-notempty'], 
'data-bv-notempty-message': $data['data-bv-notempty-message']

'data-bv-notempty':'true', 
'data-bv-notempty-message': 'This field can not be empty'

明智的

'data-bv-regexp':'true',
'data-bv-regexp-regexp':''^\d*'',
'data-bv-regexp-message': 'This field can only consist of integer value'

我在数组中添加的任何东西都应该添加到这个

data-bind="attr:{
  'data-bv-regexp':'true',
  'data-bv-regexp-regexp':''^\d*'',
  'data-bv-regexp-message': 'This field can only consist of integer value'
}"

不想使用 jQuery 或 Observable 对象

【问题讨论】:

    标签: jquery knockout.js


    【解决方案1】:

    不想使用 jQuery 或 Observable 对象

    您正在发布带有标签 的问题,但您不想使用jQuery 或observables?

    我对你的问题的解释(如果我错了,请纠正我):

    如何结合使用 viewviewmodel 中定义的属性组合来使用attr 绑定?

    例如,在您的根视图模型中有一些默认值:

    this.defaultAttributes = {
      'data-bv-notempty':'true'
    };
    

    并且您想在视图中添加这些默认值,同时还保留添加特定属性的可能性:

    <div data-bind="attr: {
        id: 'item-' + $index()
      }">
    </div>
    

    我建议你使用Object.assign 将两者合并:

    <div data-bind="attr: Object.assign({
        id: 'item-' + $index()
      }, $root.defaultAttributes)">
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-19
      • 2012-09-23
      • 2017-12-17
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 2013-10-08
      • 2013-04-17
      相关资源
      最近更新 更多