1

たとえば、まだDOMにないHTMLスニップをマージするJavaScript関数があります

<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>

この機能を改善したい。

今まで私は次のことを行います:

  • 最初のソース タグの class 属性を取得し、それをターゲットとマージします。

    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 スニペット (最初のタグ) のすべての属性を取得する方法を知っている人はいますか?

アップデート:

もちろん、ソースとターゲットを入れ替えることもできます:

  • 「attributes」で対象の 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 に答える