从数据绑定属性迭代键值对

Iterate Key Value Pairs From Data-Bind Attribute

本文关键字:键值对 迭代 属性 数据绑定      更新时间:2023-09-26

我想使用 javascript 从数据绑定属性迭代每个键和值。你有什么想法吗?我应该使用某种substring和使用el.getAttribute('data-bind')split.

下面是一个简单的例子:

<div data-bind="innerHTML: text, style: { color: color, width: '500px', height: '500px', backgroundColor: 'green' }"></div>

我想使用 pure javascript 进行迭代,从innerHTMLstyle键中逐个获取值。

将字符串转换为 json 对象。然后使用键来获取价值。您需要按如下方式更新您的 HTML。

// all values of the attribute must be quoted with single quote. i.e. It should be innerHTML : 'text' not innerHTML : text
<div data-bind="innerHTML: 'text', style: { color: 'color', width: '500px', height: '500px', backgroundColor: 'green' }"></div>
var attributeValue = document.getElementsByTagName("div")[0].getAttribute("data-bind");
var json = JSON.stringify(eval('({' + attributeValue + '})'));

然后你需要解析 json 对象,然后调用键值,如下所示:

var parsedJSON = JSON.parse(json);
alert(parsedJSON["innerHTML"]);
alert(parsedJSON["style"]["width"]);

js小提琴

如果要遍历样式属性,请尝试以下方式,

for(var attr in parsedJSON["style"]){
    alert(attr + " : " + parsedJSON["style"][attr]);
}

js小提琴

看看 Knockout.js 的绑定源代码。与所有解析一样,魔鬼在细节中,这就是为什么它如此复杂!您可以使用 lib 中的parseObjectLiteral函数knockout.js并循环访问键,例如:

 function enumerateProperties(str, items) {
     var n, i,
         arr = parseObjectLiteral(str);
     if (!str) { return 0; }
     for (i = 0; i < arr.length; i += 1) {
         if (arr[i].key) {
             n = enumerateProperties(arr[i].value, items);
             if (n == 1) {
                 items.push({
                     key: arr[i].key,
                     value: arr[i].value
                 });
             }
         }
     }
     return arr.length;
 }

这是使用敲除解析功能的工作小提琴。

这可能有点作弊,但谁在乎呢。 :P 将其包装为对象并使用eval .(这不是有效的 JSON。

eval('({' + theStuffFromDataBind + '})')