是的,有两种选择:
模板文字
JSX
模板文字
在现代 JavaScript 中,您可以使用模板文字而不是字符串文字,并且它们可以包含带有 JavaScript 表达式的占位符:
let counter = 0;
$(`<table class="main">
<tbody>
<tr>
<td>Cell ${counter++}</td>
<td>Cell ${counter++}</td>
</tr>
<tr>
<td>Cell ${counter++}</td>
<td>Cell ${counter++}</td>
</tr>
</tbody>
</table>`).appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
肯定还有一些尴尬,但它比字符串文字要好得多。
更多关于模板字面量on MDN。
JSX
JSX 不限于 React。它有它的own specification 和多个实现,例如jsx-transform。
例如,这是一个简单的 Node.js 包装器,它使用它来转译文件:
var jsx = require('jsx-transform');
console.log(jsx.fromFile("input.jsx", {
factory: 'be'
}));
如果input.jsx 是:
let counter = 0;
let table =
<table class="main">
<tbody>
<tr>
<td>Cell {counter++}</td>
<td>Cell {counter++}</td>
</tr>
<tr>
<td>Cell {counter++}</td>
<td>Cell {counter++}</td>
</tr>
</tbody>
</table>;
table.appendTo(document.body);
(请注意,这是 class="main",而不是 className="main"。使用 className 是 React 的事情,以避免出现自 2009 年 ES5 出现以来一直没有问题的问题。) em>
输出将是:
let counter = 0;
let table =
be('table', {class: "main"}, [
be('tbody', null, [
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
]),
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
])
])
]);
table.appendTo(document.body);
请注意 JSX 表达式是如何转换为对工厂函数的调用(在该示例中为 be;React 的工厂函数是 React.createElement)。您所要做的就是提供 be 函数并将转换器集成到您的构建链中(jsx-transform 预烘焙了插入 Browserify 的能力)。
您使用 jQuery 的 be 可能看起来像这样:
function be(tagName, attributes, children) {
const result = $("<" + tagName + "/>");
if (attributes) {
result.attr(attributes);
}
if (children) {
if (Array.isArray(children)) {
for (const child of children) {
result.append(child);
}
} else {
result.append(child);
}
}
return result;
}
使用转换结果的 be 函数的实时示例:
let counter = 0;
let table =
be('table', {class: "main"}, [
be('tbody', null, [
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
]),
be('tr', null, [
be('td', null, ["Cell ", counter++]),
be('td', null, ["Cell ", counter++])
])
])
]);
table.appendTo(document.body);
function be(tagName, attributes, children) {
const result = $("<" + tagName + "/>");
if (attributes) {
result.attr(attributes);
}
if (children) {
if (Array.isArray(children)) {
for (const child of children) {
result.append(child);
}
} else {
result.append(child);
}
}
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
令人惊讶的是,它真的就这么简单。