目前,我通过在双引号内 append html 向 DOM 添加元素,这会变得非常困惑并且很难阅读,特别是如果你在其中有变量,在 React 中你会使用干净的 JSX , 有没有办法在普通的 JQuery 脚本或类似 JSX 的脚本中使用 JSX?
最佳答案
是的,有两个选择:
模板文字
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 推出以来一直没有出现的问题。)
输出将是:
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 的能力)。
你的 be
使用 jQuery 可能看起来像这样:
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>
令人惊讶的是,它真的就是这么简单。
关于jquery - 使用 JQuery 很好地向 DOM 添加 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52517592/