在我的JavaScript学习曲线中,我需要学习一些更复杂的东西才能变得更好,我从带有标记的模板文字开始,但我似乎无法理解它们是如何工作的。我看过教程,看过GitHub和许多提供帮助的网站,我仍然不知道他们在说什么。我希望使用testParse函数将studyParse和parseHTML变量附加到HTML中。我尝试过使用createElement,但感觉就像一个句型,因为如果我要创建这样的div元素,我就会忽略标记模板文字的要点。我在一个项目中使用这个,这就是为什么我有一些奇怪的字符串。请彻底解释您编写的函数是如何工作的,以及它正在做什么,这样我就完全理解了。
const testInf = `Test your skills`;
const studyInf = `Study with flashcards`;
let testParse = parseHTML `<div>${testInf}</div>`;
let studyParse = parseHTML `<div>${studyInf}</div>`;
function parseHTML(){
};
console.log(parseHTML);发布于 2019-04-04 04:54:37
要使用parseHTML将这些字符串添加到HTML中,只需使用innerHTML
const testInf = `Test your skills`;
const studyInf = `Study with flashcards`;
let testParse = `<div>${testInf}</div>`;
let studyParse = `<div>${studyInf}</div>`;
function parseHTML() {
document.body.innerHTML += `${testParse}<br>${studyParse}`;
};
parseHTML();
发布于 2019-04-04 05:32:48
来自MDN
模板文字的一种更高级的形式是标记模板。标记允许您使用函数解析模板文字。标记函数的第一个参数包含一个字符串值数组。其余的参数与表达式相关。最后,您的函数可以返回被操纵的字符串(或者,它可以返回完全不同的内容,如下一个示例所述)。用于标记的函数的名称可以是您想要的任何名称。
因此,基本上您可以使用tag作为函数来解析template literal。在您的特殊情况下,您必须定义解析器函数的参数,该函数将模板文字标记为做一些事情:
const testInf = `Test your skills`;
const studyInf = `Study with flashcards`;
let testParse = parseHTML `<div>${testInf}</div>`;
let studyParse = parseHTML `<div>${studyInf}</div>`;
function parseHTML(arrayOfStrings, exp1)
{
// We will just return a string with the received arguments.
return JSON.stringify(arrayOfStrings) + exp1;
};
console.log(testParse);
console.log(studyParse);.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
因此,正如您所看到的,变量testParse和studyParse将保存解析器函数(parseHTML)返回的任何内容。现在,我们了解了它们是如何工作的,让我们看看一个与您想要做的事情相关的示例(即添加HTML内容)。
for (let i = 0; i < 5; i++)
{
console.log(putOption `Item${i}`);
}
function putOption(strings, exp1)
{
let newli = `<li>${strings[0]} ${exp1 + 1}</li>`;
document.getElementById("ul").innerHTML += newli;
return `Element ${newli} was added!`;
};.as-console-wrapper {max-height:30% !important;}
.as-console {background-color:black !important; color:lime;}<ul id="ul"></ul>
但是,您可以在不使用它们的情况下基本上实现相同的方法。
https://stackoverflow.com/questions/55507831
复制相似问题