3 回答

TA貢獻1829條經驗 獲得超13個贊
考慮使用靜態 CSS 而不是屬性 - 這大大減少了腳本所需的 JavaScript,并且更加優雅。
createElement您只需編寫 HTML 標記即可創建 DOM,這比大量的s/ appendChilds容易得多。通過分配給容器的innerHTML. 然后選擇其中需要值的元素querySelectorAll,并分配給它們的.value屬性:
const cell = document.getElementById("rows").appendChild(document.createElement("div"));
cell.innerHTML = `
<div>
<div>
<textarea></textarea>
</div>
<div>
<input>
<input>
</div>
</div>
`;
const [textarea, dateinput, timeinput] = cell.querySelectorAll('textarea, input');
textarea.value = 'mission.text';
dateinput.value = 'mission.date';
timeinput.value = 'mission.time';
#rows > div {
display: table-cell;
}
#rows > div > div {
display: inline-block; width: 270px; height: 270px; background: url(yellowNote.jpg); background-repeat: no-repeat; background-size: cover;"
}
#rows textarea {
border: unset; background: unset; resize: unset; width: 80%; height: 60%; margin-top: 20px; margin-left: 17px; padding: 10px;
}
<div id="rows"></div>
從技術上講,可以將值插入 HTML 標記內,而不是事后選擇元素并設置它們.value
,但它不太安全:
const cell = document.getElementById("rows").appendChild(document.createElement("div"));
cell.innerHTML = `
<div>
<div>
<textarea>${'mission.text'}</textarea>
</div>
<div>
<input value="${'mission.date'}">
<input value="${'mission.time'}">
</div>
</div>
`;
#rows > div {
display: table-cell;
}
#rows > div > div {
display: inline-block; width: 270px; height: 270px; background: url(yellowNote.jpg); background-repeat: no-repeat; background-size: cover;"
}
#rows textarea {
border: unset; background: unset; resize: unset; width: 80%; height: 60%; margin-top: 20px; margin-left: 17px; padding: 10px;
}
<div id="rows"></div>
如果這些值不可信,則可能允許執行任意代碼。

TA貢獻1943條經驗 獲得超7個贊
您可以使用輔助函數:
function elt(name, attrs, ...children) {
? ? let dom = document.createElement(name);
? ? for (let attr of Object.keys(attrs)) {
? ? ? ? dom.setAttribute(attr, attrs[attr]);
? ? }
? ? for (let child of children) {
? ? ? ? dom.appendChild(child);
? ? }
? ? return dom;
}
這樣,您可以更自然地嵌套元素,如下所示:
const table = elt('div', {id: 'cell', style: 'display: table-cell;'}, [
? ? elt('div', {style: '...'},
? ? ? ? elt('textarea', {id: 'ff', style: '...'}),
? ? ? ? elt('div', {style: 'display:inline-block;'}),
? ? ? ? // other children
? ? )
]);

TA貢獻1801條經驗 獲得超8個贊
基本上
var cell = document.createElement("div")
cell.innerHTML = `
<div style=" display: inline-block; width: 270px; height: 270px; background: url(yellowNote.jpg); background-repeat: no-repeat; background-size: cover;">
<textarea id="ff" style="border: unset; background: unset; resize: unset; width: 80%; height: 60% ; margin-top: 20px; margin-left: 17px; padding: 10px;"></textarea>
<div style="display:inline-block;">
<input id="mr" type="date">
<input id="mc" type="time">
</div>
</div>`
基本上做同樣的事情
- 3 回答
- 0 關注
- 183 瀏覽
添加回答
舉報