2012-07-04 238 views
-1

我想在javascript中創建一個內容變量,其中將包含具有特定值的html標記。 如何在按下按鈕時將其放入div中。如何使用javascript寫入到div

例如:

這就是我想用一個內容:

var contentString = '<div id="info">'+ 
'<h2><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Info:</b></h2>'+ 
'<div id="bodyContent">'+ 
'<div style=width:220px;display:inline-block;>'+ 
'<p>&nbsp; Name: '+ this.name + '</p>' + 
'<p>&nbsp; Last name: '+ this.last+ '</p>' + 
'<p>&nbsp; 
'</div>'+ 
'</div>'+ 
'</div>'+ 
'</form>'; 

而且我希望把它變成:<div id=something"></div> 在javascript中我能有這樣的事情:

$("#button").on('click', function() { 
// What to put in here? 
}); 
+0

請大家注意,所有的答案迄今建議調用.html屬性是喜歡做.innerHTML。我建議你不要直接編寫HTML,而應該使用appendChild和createElement。 –

回答

8

如何在按下按鈕時將其放入div中。

像這樣:

$("#button").on('click', function() { 
    $('#something').html(contentString); 
}); 

更多信息有關html();

1

你應該修正你的標記。你有不平衡的元素,並且你不能在沒有轉義的情況下在字符串中有新的行。試試這個:

var contentString = '<div id="info">'+ 
'<h2><b style="text-indent: 40px">Info:</b></h2>'+ 
'<div id="bodyContent">'+ 
'<div style="width:220px;display:inline-block;">'+ 
'<p style="text-indent: 1em">Name: '+ this.name + '</p>' + 
'<p style="text-indent: 1em">Last name: '+ this.last+ '</p>' + 
'</div>'; 

請注意,我跳過&nbsp;並用樣式屬性替換它們。不過,你真的應該把這些樣式放在樣式表中。

$("#button").on('click', function() { 
$('#something').html(contentString); 
}); 

請記住,在contentString的變量將不會被計算時的觸發按鈕單擊事件,這意味着this.name和this.last不會改變。你還需要點擊更新這些值嗎?

2

如果我沒有誤會,那麼這將工作:

$("#button").on('click', function() { 
    $('#something').html(contentString); 
}); 

這不,當然,假設你有一個的buttonid元素(雖然我認爲你這樣做,否則你止跌沒有把這個jQuery)。

JS Fiddle demo

參考文獻:

2

它是這樣的:

$("#button").on('click', function() { 
    $("#something").html(contentString); 
});