我想向“myContent1”添加多行代码,而不必复制它,因为这可能非常乏味。有更有效的方法吗?谢谢!
function getCode(form){
myContent1 = document.inputForm.myContent1.checked;
output =
'<!DOCTYPE html>\n' +
'<html>\n' +
'<body>\n' +
((myContent1) ? '<div>content 1</div>' : '') + '\n' +
((myContent1) ? '<div>content 2</div>' : '') + '\n' +
'' +
'<\/body>\n' +
'<\/html>\n';
document.inputForm.source.value = output;
return output;
}
最佳答案
您可以使用 ES6 模板文字来实现相同的目的。
这是一个示例代码。我也修改了代码来检查条件。
getCode()
function getConditionalTemplate(x, y) {
if (Number(x) > Number(y)) {
return `<div>content1</div>`
} else {
return `<div>content2</div>`
}
}
function getCode() {
const myContent1 = document.getElementById('inputForm');
const x = 10000;
const y = 200;
const output =
`<!DOCTYPE html>
<html>
<body>
${getConditionalTemplate(`${x}`,`${y}`)}
<\/body>
<\/html>`
myContent1.innerHTML = output;
}
<div id="inputForm">
</div>
关于javascript - JS中的多行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44793390/