0

dom 要素をレンダリングするための関数を作成しようとしていますが、追加する前に複数の dom 要素を組み立てるのに行き詰まっているようです。

私はこれを試しました:http://jsfiddle.net/RruyA/1/ そして、私の画像をリンクでラップすることができないようです。

そして、innerHTMl が現在 (フィドルでコメントでマークされている) 場所で appendChild() を使用すると、無効なポインター エラーが発生します。

何がうまくいかないのかについてはいくつかの理論がありますが、まだ解決策はありません。助けてください!

完全なコードは次のとおりです。

(function () {
    "use strict";

    function tag (name, attributes, contents) {
      var tag = {};
      tag.name = name;
      tag.attributes = attributes;
      tag.contents = contents
      tag.create = function () {
        tag.element = document.createElement(tag.name);
        for (var prop in tag.attributes) {
          tag.element.setAttribute(prop, tag.attributes[prop]);
        }
        // This is the problem:
        tag.element.innerHTML = contents;
      }
      tag.render = function () {
        document.body.appendChild(tag.element);
      }
      return tag;
    }

    var p = tag('p', {'id':'details', 'class':'red nice lovely'}, 'Once upon a time in a golden castle on a silver cloud...');
    var img = tag('img', {'src':'http://miyazakihayao.blog.com/files/2010/05/castle-in-the-sky-x1.jpg', 'width': '200px', 'alt':'Golden Castle'});
    img.create();
    img.render();
    p.create();
    p.render();
    var a = tag('a', {'href':'http://google.com', 'target':'_blank'}, img.element);
    a.create();
    a.render();


}());
4

1 に答える 1

1

問題は、テキストと HTML 要素を同じ方法で追加しようとしていることです。innerHTML要素は強制的に文字列に変換され、HTML 要素が追加されますが、テキストは正常に機能しますが、文字列appendChildを TextNode でラップする必要があります。

したがって、これらのタイプから選択でき、正常に機能します。

// This is a solution
if (contents) {
  if (contents instanceof HTMLElement) {
    tag.element.appendChild(contents);
  }
  else {
    tag.element.innerHTML = contents;
  }
}
于 2013-03-11T13:47:09.363 に答える