2017-12-20 17 views
0

ではありません。キャッチされない例外TypeErrorは:tplContent.importNodeは、私は本からの次のコードを著書「WebコンポーネントMITポリマー」を読んでみましたよ機能

<!doctype html> 
<html> 
<body> 
<template id="tpl"> 
    <h1 class="title"></h1> 
    <div class="body"></div> 
</template> 
<script> 
    var tplContent = document.getElementById("tpl").content; 
    var node = tplContent.importNode(true); 
    node.querySelector("h1").textContent = "Hallo Welt"; 
    node.querySelector("div").textContent = "Ich komme aus einem Template"; 
    document.body.appendChild(node); 
</script> 
</body> 
</html> 

が、私はちょうど二JSで停止します

Uncaught TypeError: tplContent.importNode is not a function

私はUbuntuでGoogle Chromeのバージョン63.0.3239.84を使用しています。 誰かがこのお手伝いできますか?

よろしく、 アルトゥル

答えて

1

importNodeは、ドキュメント内の要素ではない、documentに呼び出されなければなりません。 MDNから

<!doctype html> 
 
<html> 
 
<body> 
 
<template id="tpl"> 
 
    <h1 class="title"></h1> 
 
    <div class="body"></div> 
 
</template> 
 
<script> 
 
    var tplContent = document.getElementById("tpl").content; 
 

 
    // importNode is a method of document: 
 
    var node = document.importNode(tplContent, true); 
 

 
    node.querySelector("h1").textContent = "Hallo Welt"; 
 
    node.querySelector("div").textContent = "Ich komme aus einem Template"; 
 
    document.body.appendChild(node); 
 
</script> 
 
</body> 
 
</html>

<template>here document.importNode()を使用して上の

The Document method importNode() creates a new copy of the specified Node or DocumentFragment from another document so that it can be inserted into the current Document. It is not yet included in the document tree; to do that, you need to call a method such as appendChild() or insertBefore() .

追加情報。

1

あなたはここでエラーを持っている:

var node = tplContent.importNode(true); 

tpl使用したい場合は関数にimportNode()

を持っていないimportNode

var node = document.importNode(tplContent, true); 

<!doctype html> 
 
<html> 
 
<body> 
 
<template id="tpl"> 
 
    <h1 class="title"></h1> 
 
    <div class="body"></div> 
 
</template> 
 
<script> 
 
    var tplContent = document.getElementById("tpl").content; 
 
    var node = document.importNode(tplContent, true); 
 
    node.querySelector("h1").textContent = "Hallo Welt"; 
 
    node.querySelector("div").textContent = "Ich komme aus einem Template"; 
 
    document.body.appendChild(node); 
 
</script> 
 
</body> 
 
</html>

0

代わりに<template>contentcloneNode()メソッドを使用できます。

var tplContent = document.getElementById("tpl").content; 
var node = tplContent.cloneNode(true); 
関連する問題