使用jquery插入html代码

问题描述:

我是jquery和html的新手。我试图插入在jquery中的代码到html代码中的class =“content”中,我检查控制台并且它到达loadDoc()函数。我用.html和.append试过这两个都不行。使用jquery插入html代码

HTML代码

<section id="doc" class="main"> 
     <div class="content"> 
     </div> 
    </section> 

jQuery代码

function loadDoc(){ 
     console.log("Load Doc"); 
     var content = '<header>This is the header</header><article>' + 
     '<p>This is the content form loadDoc() </p></article>'; 
     $("section#doc.content").append(content); 
    } 

你想#doc .content而不是section#doc.content,因为你的目标是html插入地处#doc元素.content元素。

function laodDoc(){ 
    console.log("Load Doc"); 
    var content = '<header>This is the header</header><article>' + 
    '<p>This is the content form loadDoc() </p></article>'; 
    $("#doc .content").append(content); 
} 

您的jQuery选择器不正确。取而代之的

$("section#doc.content") 

你需要有

$("section#doc .content") 

这是因为.content元素是section#doc内。

+0

我很快就被重写它应该在的问题我的道歉 – user3464613

+0

loadDoc() @ user3464613明白了。看到我编辑的答案的第二部分 - 你的jQuery选择器也有错误。 –

使用:

$("#doc .content").html(content); 

使用jQuery和更简单的代码:

var content = '<header>This is the header</header><article>' + 
     '<p>This is the content form loadDoc() </p></article>'; 
$(".content").html(content); 

小提琴这里:http://jsfiddle.net/9oneuqf9/

+0

他们可能不想更新每个称为'content'的类。 –

+0

好吧,在这种情况下,可以有一个扩展选择器“section#doc.content” –

+0

我的错误输入太快......正确的语法:“section#doc .content”小提琴在这里:http://jsfiddle.net/9oneuqf9/1 / –