2015-11-15 3 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-I хотел бы добавить, выглядит так:

<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, второй пытается найти тег HTML на DOM и добавить его ~

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

То есть, если вы хотите разместить свой новый HTML после block-1 вы выбираете блок-1 и вызовите InsertAfter() на нем, передавая новый HTML в качестве параметра -

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

Или вы могли держать заказ у вас есть, если это более понятно для вас, но и использовать .after()

$(html).after($('#block-1')); 
Смежные вопросы