這個問題在這里已經有了答案: 如何在 HTML 中使用這個 JavaScript 變數? (8 個回答) 2 分鐘前關閉。
除了使用innerhtml之外,還有什么方法可以將JS變數放入HTML部分,因為我不喜歡使用create element,而是使用這樣的原始html:
var infoBar = document.createElement('div')
infoBar.innerHTML = `
<div class="card-body"">
<h2></h2>
</div>
`
有什么方法可以將變數放入標題標簽?比如 Jinja:
var i = 'hello'
<h2>{{i}}</h2>
uj5u.com熱心網友回復:
你到底在問什么?如何在沒有 createElement 的情況下寫入 innerHTML?
如果是這樣:
<h1 id="identificator"></h1>
var string = "Hello"
var id = document.getElementById("identificator")
id.innerHTML = string
uj5u.com熱心網友回復:
PS 我將使用以下代碼行作為每個示例的一部分
let word = "hello";
所以有幾種方法可以解決它:
- 用
document. write(word)寫下來
document.write(word); // This method will replace the whole document with whatever you pass
- 使用
docment.createElement()
您將創建我們想要添加 ex 的 HTML 元素:
<div class="card-body">
<h2></h2>
</div>
所以我們會那樣做
let divElement = document.createElement("div");
let h2Element = document.createElement("h2");
divElement.appendChild(h2Element);
document.body.appendChild(divElement); // This will place the created element at the end of the body
- 使用
innerHTML
document.getElementById("identifier").innerHTML = '<div ><h2>' word '</h2></div>';
- 使用
innerHTML和模板文字
document.getElementById("identifier").innerHTML = `<div class='card-body'><h2>${word}</h2></div>`;
- 使用像knockoutjs這樣的 JS 庫
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.word = "hello";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
<p>Word: <strong data-bind="text: word">todo</strong></p>
uj5u.com熱心網友回復:
由于您使用的是模板文字,因此您可以在那里替換變數。
var infoBar = document.createElement('div');
var i = 'hello';
infoBar.innerHTML = `
<div ">
<h2>${i}</h2>
</div>
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483686.html
標籤:javascript html
上一篇:無法洗掉頂部網站中的白條
