2015-11-15 25 views
3

我有以下代碼:正確的方式來添加HTML將jQuery/JavaScript的

<section class="section1"> 
    //Section one content 
</section> 
<section class="section2"> 
    <h4>Some Title</h4> 

    <input type="hidden" class="keys" value="1"/> 
    <div id="block-close-1"></div> 
    <div class="block" id="block-1"> 
      //Block content 
    </div> 

</section> 

<section class="section3"> 
    //Section3 content  
</section> 

我想要做的是採取一些html和「塊1」

的HTML我後插入要添加看起來像這樣:

<input type="hidden" class="keys" value="2"/> 
    <div id="block-close-2"></div> 
    <div class="block" id="block-2"> 
      //Block content 
    </div> 

我已經試過這樣:

var html = '//code as above'; 
$("html").insertAfter("#block-1"); 

我得到的錯誤是這樣的:

Uncaught HierarchyRequestError: Failed to execute 'insertBefore' on 'Node': The new child element contains the parent.

我也試過這樣: 的document.getElementById( '#塊4')的appendChild(HTML);

錯誤:

Uncaught TypeError: Cannot read property 'appendChild' of null

什麼是新的HTML添加到現有的HTML的正確方法?

+1

在你的情況下'html'是一個變量,所以你必須使用'$(html).insertAfter(「#block-1」);'(不含引號(如@Elentriel回答)這個'$(「

some html...
」).insertAfter(「#block-1」);' – mineroot

回答

5

你想$(html)$("html")

首先嚐試添加變量HTML的內容,第二試圖找到對DOM的標記HTML,並將其添加〜

+0

好吧發現... – HappyCoder

+0

但當然我的樂趣:) 如果它幫助你,將其作爲接受的答案 – Elentriel

5

本地JavaScript的方法是這樣的:

document.getElementById("block-1").insertAdjacentHTML("afterend",html);

jQuery的方法:

$("#block-1").after(html);

+1

加一個本地js :) – AtheistP3ace

5

從jQuery的文檔insertAfter ...

The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

,如果你想block-1後,把你的新的HTML,這是你選擇的塊1,並調用它insertAfter(),並傳遞新HTML作爲參數 -

$('#block-1').insertAfter($(html)); 

,你可以繼續你如果是更直觀的你的命令,但使用.after()

$(html).after($('#block-1'));