标记的模板字面量混淆

Tagged template literals confusion

我正处于 JavaScript 学习曲线的关键点,我需要学习一些更复杂的东西才能变得更好,我从标记的模板文字开始,但我似乎做不到让我全神贯注于它们的工作原理。我看过教程,看过 GitHub 和许多提供帮助的网站,但我仍然不知道他们在说什么。我想使用 parseHTML 函数将 testParsestudyParse 变量附加到我的 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);

要使用 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();

来自MDN

A more advanced form of template literals are tagged templates. Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions. In the end, your function can return your manipulated string (or it can return something completely different as described in the next example). The name of the function used for the tag can be whatever you want.

所以,基本上您可以使用 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;}

因此,正如您所见,变量 testParsestudyParse 将保存解析器函数 (parseHTML) returns 的任何内容。现在,我们了解了它们的工作原理,让我们看一个与您想要执行的操作相关的示例(即添加 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>

但是,您基本上可以在不使用它们的情况下实现相同的方法。