简体   繁体   English

js中的剔除数据绑定语法(不是HTML)

[英]knockout data-bind syntax in js ( not HTML)

I understand I can create bindings using the following syntax in the dom: 我了解我可以在dom中使用以下语法创建绑定:

 <span id="namespan" data-bind="text: personName"> 

Working example here: https://jsfiddle.net/m14mohda/ 这里的工作示例: https : //jsfiddle.net/m14mohda/

But can I create such a span element in js? 但是我可以在js中创建这样的span元素吗? ie using something like: 即使用类似的东西:

createSpans = function (){
    var s = document.createElement('span')
    s.id = "namespan"
    s.data-bind ="text: personName" -----> ????
    document.body.appendChild(s)
}

The DOM Element API offers two ways of doing this. DOM元素API提供了两种方法。 The more general one, that should work with any custom attribute is using the setAttribute method. 适用于任何自定义属性的更通用的方法是使用setAttribute方法。

var s = document.createElement('span');
s.setAttribute("someAttribute", "someValue");
s.setAttribute("data-bind", "text: personName");
document.body.appendChild(s);

creates the element 创建元素

<span someAttribute="someValue" data-bind="text: personName"></span>

Specifically for attributes that are data- prefixed, the specification includes the shorthand property accessor dataset . 特别是对于以数据为前缀的属性,规范包括速记属性访问器dataset

var s = document.createElement('span');
s.dataset.someAttribute = "someValue"; // won't work as expected       
s.dataset.bind = "text: personName";
document.body.appendChild(s);

which creates the element 创建元素

<span data-someAttribute="someValue" data-bind="text: personName"></span>

So you can see that dataset takes the data- prefix for granted. 因此,您可以看到dataset数据前缀视为理所当然。 data- attribute values can then be accessed and assigned through dataset by stripping the data- part. 然后,通过剥离数据部分,可以通过dataset访问和分配数据属性值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM