xCreate方法的目的是通过JSON来定义HTML,以方便开发者在Javascript中创建DOM。常用的与xCreate相关的方法共有如下几个:
- $.xCreate() - 根据JSON创建DOM元素并返回。
- $().xAppend() - jQuery扩展,根据JSON创建DOM元素并添加到当前jQuery包装的DOM中。
- $().xInsertBefore() - jQuery扩展,根据JSON创建DOM元素并添加到当前jQuery包装的DOM之前。
- $().xInsertAfter() - jQuery扩展,根据JSON创建DOM元素并添加到当前jQuery包装的DOM之后。
下面的示例都将以xCreate()为例来说明,具体请参考各个方法的API文档:xCreate
简单JSON
tagName表示DOM的节点名,content表示DOM节点的内容
$.xCreate({
tagName: "div",
content: "Hello World!"
});创建多个对象
如果要创建的某个DOM的tagName是DIV,那么相应的JSON对象的tagName是可以省略的。
$.xCreate([
{
content: "Hello World!"
},
{
tagName: "input",
value: "This is an input"
}
]);定义Style
style既可以通过字符串定义,也可以通过子JSON来定义。
$.xCreate([
{
content: "Style by String",
style: "color:red; font-weight:bold"
},
{
content: "Style by JSON",
style: {
color: "blue",
fontStyle: "italic"
}
}
]);子对象
当content的值是子JSON对象或数组,就表示要定义DOM的子节点而不是文本内容。
$.xCreate([
{
content: {
tagName: "input",
type: "text"
}
},
{
content: [
"Some text ",
{
tagName: "input",
type: "checkbox"
},
{
tagName: "input",
type: "checkbox"
}
]
}
]);空节点的简写
有时我们只需要创建一个空的节点,那么只要利用“^”开头的字符串指定好节点名就可以了。
$.xCreate([ "^input", "^hr" ]);
创建Table
$.xCreate({
tagName: "table",
style: {
width: 200
},
content: [
{
tagName: "tr",
style: "height: 30px",
content: ["^td", "^td"]
},
{
tagName: "tr",
style: "height: 30px",
content: ["^td", "^td"]
}
]
});绑定事件
如果某个属性的值是一个Function则表示我们绑定一个事件。
$.xCreate({
tagName: "button",
content: "Click Me",
click: function() {
alert("Hello World!");
}
});
