使用object-literal创建具有属性的元素

cll*_*pse 2 jquery dom

从1.4版的jQu​​ery开始; 你已经能够使用对象文字创建一个元素,定义元素属性...

$("<div />",
{
    id: "test",
    name: "test",
    class: "test-class"
});
Run Code Online (Sandbox Code Playgroud)

除了为元素分配一些属性之外; 我想添加一些内嵌样式.这是可能的,使用对象文字?...我正在做一些事情:

$("<div />",
{
    id: "test",
    name: "test",
    class: "test-class",
    style: {
        width: "100px",
        height: "100px",
        background-color: "#fff"
    }
});
Run Code Online (Sandbox Code Playgroud)

And*_*y E 10

您可以将方法名称和参数传递给将在对象上执行的映射.

$("<div />",
{
    id: "test",
    name: "test",
    class: "test-class",
    css: {
        width: "100px",
        height: "100px",
        backgroundColor: "#fff"
    }
});
Run Code Online (Sandbox Code Playgroud)

文档:

此外,可以传入任何事件类型,并且可以调用以下jQuery方法:val,css,html,text,data,width,height或offset.

  • +1使用已经内置的东西. (2认同)