本文目錄一覽:
求助如何使用js向div追加html代碼
!DOCTYPE html
html
head
script src=”jquery.js”/script
div id=”dictionary”
/div
div class=”letters”
div class=”letter” id=”letter-a”
h3a href=”entries-a.html”A/a/h3
/div
div class=”letter” id=”letter-b”
h3a href=”entries-a.html”B/a/h3
/div
div class=”letter” id=”letter-c”
h3a href=”entries-a.html”C/a/h3
/div
div class=”letter” id=”letter-d”
h3a href=”entries-a.html”D/a/h3
/div
!– and so on —
/div
/head
body
script
$(document).ready(function() {
$(‘#letter-c a’).click(function(event) {
event.preventDefault();
$.getScript(‘c.js’);
});
});
/script
/body
/html
將寫好的c.js文件放置同一個目錄下面
var entries = [
{
“term”: “CALAMITY”,
“part”: “n.”,
“definition”: “A more than commonly plain and…”
},
{
“term”: “CANNIBAL”,
“part”: “n.”,
“definition”: “A gastronome of the old school who…”
},
{
“term”: “CHILDHOOD”,
“part”: “n.”,
“definition”: “The period of human life intermediate…”
}
//省略的內容
];
var html = ”;
$.each(entries, function() {
html += ‘div class=”entry”‘;
html += ‘h3 class=”term”‘ + this.term + ‘/h3’;
html += ‘div class=”part”‘ + this.part + ‘/div’;
html += ‘div class=”definition”‘ + this.definition + ‘/div’;
html += ‘/div’;
});
$(‘#dictionary’).html(html);
//$(‘#dictionary’).append(html);
這裡的$(‘#dictionary’).html(html);可以直接將需要的代碼放入到指定的div內 (div id=”dictionary”)
也可以通過$(‘#dictionary’).append(html);將代碼附加到指定的div內 (div id=”dictionary”)
JS如何在頁面中插入HTML代碼
步驟
1、新建一網頁文件「sample.html”,用記事本或其它文本編輯軟體(如UltraEdit)打開,輸入如圖所示的HTML代碼。該網頁文件包括一個藍色的字元串,一個按鈕和一個文本框。
2、JS代碼可插入到」head”標籤之間。編寫Javascript代碼,代碼內容如圖所示,並將該段代碼複製到網頁文件」sample.html「中標籤」head”和「/head之間,然後查看網頁文件的顯示內容。
如何在 JS 中嵌入 HTML 代碼
思路,在JS中定義要嵌入的html代碼,然後通過js進行嵌入即可。
html
head
script
function insert(){
‘定義代碼
var insertText = “tabletrtdany thing/td/tr/table”;
』從html的標籤中取得要插入的id進行innerHTML
document.getElementById(“insert”).innerHTML = document.getElementById(“insert”).innerHTML+insertText;
}
/script
/head
body
button onclick=”insert()”Insert/button
div id=”insert”/div
/body
/html
innerHTML在JS是雙向功能:獲取對象的內容 或 向對象插入內容;
如:div id=”aa”這是內容/div ,可以通過 document.getElementById(‘aa’).innerHTML 來獲取id為aa的對象的內嵌內容;
也可以對某對象插入內容,如 document.getElementById(‘abc’).innerHTML=’這是被插入的內容’; 這樣就能向id為abc的對象插入內容。
使用js向網頁中寫入html內容
js可以向網頁中寫入html內容,方法是調用write方法向document的節點中寫入html元素
以下展示兩個實例
1.在網頁上寫入一個標題為hello的元素
效果如圖:
2.在網頁上寫入一個九九乘法表
在js中可以使用上面的 h1 hello /h1 這樣的開始標籤和閉合標籤在一起的標籤寫法,也可以將開始標籤和閉合標籤分開來寫,例如本例。
本例的邏輯是用table標籤建立一個表,然後用for循環分別計算九九乘法的結果,在寫入結果的前後用tr標籤形成一行,計算結果的時候用td標籤形成一列
效果圖:
通過chrome瀏覽器右鍵檢查,可以看到的確寫入了一個九九乘法表的table到網頁中
注意:
在進行字元串拼接的時候如果沒有處理好,會出現 SyntaxError: missing ) after argument list 的錯誤,需要謹慎對待,具體問題具體對待,解決方法可以參考下面的資料或者自行google
1. SyntaxError: missing ) after argument list
2. js中出現missing ) after argument list
3. JavaScript: SyntaxError: missing ) after argument list [closed]
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/270852.html