1

例如,我有一个 JavaScript 函数,它合并了一个在 DOM 中还没有的 html 片段

<div class="one two"><input /><span name="abc">Text</span></div>

带有 DOM 节点/标签

<div id="aaa" class="another"></div>

结果是:

<div id="aaa" class="one two another"><input /><span name="abc">Text</span></div>

我想改进这个功能。

到目前为止,我执行以下操作:

  • 它采用第一个源标记的类属性并将其与目标合并:

    classes = $(source).first().attr("class");
    this.addClass(classes);
    
  • 它将源子标签附加到目标:

    this.append($(source).first().children());
    

现在我想添加到这个功能:

   Take all attribute (not "class") of the first source tag and add it to the
   first target tag (overwrite if it exists).

问题是,我不能采用“属性”,因为截断的源代码还没有在 DOM 中。到目前为止,我的解决方案不是很漂亮:对于每个非常常见的属性,我都有一个额外的行:

tabindex = $(source).first().attr("tabIndex");
this.attr("tabIndex", tabindex);

wrap = $(source).first().attr("wrap");
this.attr("wrap", wrap);

有谁知道如何获取这样一个 html 片段(第一个标签)的所有属性?

更新:

当然我可以交换源和目标:

  • 使用“属性”读取目标 DOM 标记的所有属性。
  • 将这些属性添加到代码片段的第一个标记中,该标记尚未在 DOM 中。
  • 将 DOM 标记替换为 html 片段。

但是有更优雅的解决方案吗?

4

1 回答 1

1

通过从实际的 DOM 对象访问它们,您应该能够很容易地从片段中读取属性:

​var $target = $('#aaa');​​​​​​​​
$source = $('<div class="one two"><input /><span name="abc">Text</span></div>');​

// iterate over attributes of $source
// we use $source.get(0) to get the DOM fragment itself
for (var i = 0, attributes = $source.get(0).attributes, item; item = attributes[i]; ++i) {
    if (item.name == 'class') {
        // special case for class
        $target.addClass(item.nodeValue);
    } else {
        // otherwise overwrite attribute of target with source
        $target.attr(item.name, item.nodeValue);
    }
}
// finally append the children from source
​$target.append($source.children());​
于 2012-11-14T15:02:45.007 回答