我想使用jQuery append生成以下HTML字符串。手动编写代码对我来说太麻烦了。
<div>
<label>Name (Optional)</label>
<input type='text' class='form-control' id='job-name'/><br />
<label>Quick Schedule</label><br />
<a class="btn btn-primary" onclick="schedule = '@hourly'; job_string();">Hourly</a>
<a class="btn btn-primary" onclick="schedule = '@daily'; job_string();">Daily</a>
<a class="btn btn-primary" onclick="schedule = '@weekly'; job_string();">Weekly</a>
<a class="btn btn-primary" onclick="schedule = '@monthly'; job_string();">Monthly</a>
<a class="btn btn-primary" onclick="schedule = '@yearly'; job_string();">Yearly</a><br /><br />
<div class="row">
<div class="col-md-2">Minute</div>
<div class="col-md-2">Hour</div>
<div class="col-md-2">Day</div>
<div class="col-md-2">Month</div>
<div class="col-md-2">Week</div>
</div>
<div class="row">
<div class="col-md-2"><input type="text" class="form-control" id="job-minute" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-hour" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-day" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-month" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-week" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><a class="btn btn-primary" onclick="set_schedule();">Set</a></div>
</div>
</div>
例如,应使用以下格式编写该文件。
$('<div/>').append(
).append(
) ....
使用jQuery append创建如上所述的HTML的最佳方法是什么?铅在这里非常感谢。
答案 0 :(得分:6)
您可以用树状数据结构表示HTML。完成后,您可以遍历树,并为每个节点创建相应的元素并将其附加到目标元素。
功能样式编程似乎非常适合以最少的代码创建上述对象。您可以抽象地创建具有功能组合的复杂结构。此外,您可以使用数组和高阶函数(例如map)来批量创建元素。
要让您了解其完成方式,请考虑以下用于表示节点(元素)的模型(接口):
interface Node {
tag: string;
classNames: string[];
attrs: {
[key: string]: string;
};
eventHandlers: {
[key: string]: (...params: any[]) => any;
};
children: Node[];
textChildren: string[];
}
注意:上面的类型定义用Typescript编写。显然,您可以忽略类型并实现我在普通JavaScript中描述的内容。
现在考虑以下标记:
<div class="row">
<div class="col-md-2"><input type="text" class="form-control" id="job-minute" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-hour" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-day" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-month" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><input type="text" class="form-control" id="job-week" value="*" onclick="this.select();"/></div>
<div class="col-md-2"><a class="btn btn-primary" onclick="set_schedule();">Set</a></div>
</div>
让我们定义一些辅助函数,以便我们可以更轻松地创建等效树:
const createRow = (children) => ({
tag: "div",
classNames: ["row"],
attrs: {},
eventHandlers: {},
children,
textChildren: []
});
const createCol = (cls, children) => ({
tag: "div",
classNames: [cls],
attrs: {},
eventHandlers: {},
children,
textChildren: []
});
const createFormInput = (attrs, eventHandlers) => ({
tag: "input",
attrs,
classNames: ["form-control"],
eventHandlers,
children: [],
textChildren: []
});
const createFormInputTextInCol = id =>
createCol("col-md-2", [
createFormInput(
{
type: "text",
id,
value: "*"
},
{
click() {
this.select();
}
}
)
]);
const createAnchorButton = (text, eventHandlers) => ({
tag: "a",
attrs: {},
classNames: ["btn", "btn-primary"],
eventHandlers,
children: [],
textChildren: [text]
});
使用上面定义的功能,创建等效树很容易:
const row = createRow([
...["job-minute", "job-hour", "job-day", "job-month", "job-week"].map(
createFormInputTextInCol
),
createCol("col-md-2", [
createAnchorButton("Set", {
click() {
// TODO: define set_schedule
// set_schedule();
}
})
])
]);
并将此对象转换为(用JQuery包装)元素,您可以执行以下操作:
const toElement = node => {
const element = $(`<${node.tag}>`);
Object.keys(node.attrs).forEach(key => {
element.attr(key, node.attrs[key]);
});
element.addClass(node.classNames.join(" "));
Object.keys(node.eventHandlers).forEach(key => {
element.on(key, function(...args) {
node.eventHandlers[key].call(this, ...args);
});
});
node.textChildren.map(text => document.createTextNode(text)).forEach(e => element.append(e));
node.children.map(toElement).forEach(e => element.append(e));
return element;
};
$('<div />').append(toElement(row));
演示
const createRow = (children) => ({
tag: "div",
classNames: ["row"],
attrs: {},
eventHandlers: {},
children,
textChildren: []
});
const createCol = (cls, children) => ({
tag: "div",
classNames: [cls],
attrs: {},
eventHandlers: {},
children,
textChildren: []
});
const createFormInput = (attrs, eventHandlers) => ({
tag: "input",
attrs,
classNames: ["form-control"],
eventHandlers,
children: [],
textChildren: []
});
const createFormInputTextInCol = id =>
createCol("col-md-2", [
createFormInput({
type: "text",
id,
value: "*"
}, {
click() {
this.select();
}
})
]);
const createAnchorButton = (text, eventHandlers) => ({
tag: "a",
attrs: {},
classNames: ["btn", "btn-primary"],
eventHandlers,
children: [],
textChildren: [text]
});
const row = createRow([
...["job-minute", "job-hour", "job-day", "job-month", "job-week"].map(
createFormInputTextInCol
),
createCol("col-md-2", [
createAnchorButton("Set", {
click() {
// TODO: define set_schedule
// set_schedule();
}
})
])
]);
const toElement = node => {
const element = $(`<${node.tag}>`);
Object.keys(node.attrs).forEach(key => {
element.attr(key, node.attrs[key]);
});
element.addClass(node.classNames.join(" "));
Object.keys(node.eventHandlers).forEach(key => {
element.on(key, function(...args) {
node.eventHandlers[key].call(this, ...args);
});
});
node.textChildren.map(text => document.createTextNode(text)).forEach(e => element.append(e));
node.children.map(toElement).forEach(e => element.append(e));
return element;
};
$(document).ready(() => {
const rowElement = toElement(row);
$("#wrapper").html(rowElement);
$("#outerHtml").text($("#wrapper").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<h2>Generated HTML</h2>
<pre id="outerHtml"></pre>
<h2>Appended Element</h2>
<div id="wrapper"></div>