2015-09-25 70 views
-2

我是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); 
    } 

回答

1

你想#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); 
} 
1

您的jQuery選擇器不正確。取而代之的

$("section#doc.content") 

你需要有

$("section#doc .content") 

這是因爲.content元素是section#doc內。

+0

我很快就被重寫它應該在的問題我的道歉 – user3464613

+0

loadDoc() @ user3464613明白了。看到我編輯的答案的第二部分 - 你的jQuery選擇器也有錯誤。 –

0

使用:

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

使用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 / –