2013-12-14 66 views
2

我想知道如何在jQuery之前插入一個HTML元素。 能夠從輸入中獲取新元素的內容也很重要。 類似的東西,但工作:在另一個jQuery之前插入一個HTML元素

var input = $("#theInput").val(); 

var content = document.createElement("p"); 

content.appendChild(document.createTextNode(input)); 

$("div").insertBefore(content); 
+5

你混了順序,'$(內容).insertBefore( 「格」);',或者只是'$( 「格」)前(的內容);' – adeneo

回答

2

試試這個:

$("div").prepend(content); 
1

見下面的例子:

HTML結構:

<div class="container"> 
    <h2>Greetings</h2> 
    <div class="inner">Hello</div> 
</div> 

的Jquery:

$(".inner").before("<p>Test</p>"); 

結果(HTML):

<div class="container"> 
    <h2>Greetings</h2> 
    <p>Test</p> 
    <div class="inner">Hello</div> 
</div> 

編輯:

請參見下面的示例,它從文本框取值之前

HTML結構插入:

<div id="content"> 
<input type="text" value="textboxvalue" > <br/><br/> 
<span>Insert text box value befor this one</span>  
</div> 

查詢:

var inputval = $("#content input").val(); 
$("#content span").before("<p>" + inputval + "</p>"); 
+0

它。一切都好,就像我在谷歌找到的其他例子。但是,你能幫我解釋一下如何將輸入變量添加到該段落中。因爲在這裏它被添加到HTML文件,如文本,我不知道它是否可以修改 – user3023071

+0

我已經在我的評論中添加了上面的一個新示例,工作jsfiddle鏈接是http://jsfiddle.net/Np8U8/2 / –

0

JSFIDDLE

選擇1 - 只需使用jQuery:

var input = $("#theInput").val(); 
$("<p />")      // Create a paragraph element. 
    .text(input)    // Set the text inside the paragraph to your input. 
    .insertBefore($("div")); // Insert the paragraph before the div element(s). 

選項2 - 修改代碼:

var input = $("#theInput").val(), 
    content = document.createElement("p"); 
content.appendChild(document.createTextNode(input)); 
$(content).insertBefore($("div")); 

選項2a - 或者你可以改變最後一行:

$("div").before(content); 
相關問題