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

时间:2010-08-06 12:10:29

标签: jquery dom

从jQuery 1.4版开始;您已经能够使用对象文字创建元素,定义元素属性...

$("<div />",
{
    id: "test",
    name: "test",
    class: "test-class"
});

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

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

4 个答案:

答案 0 :(得分:10)

您可以将方法名称和参数传递给将在对象上执行的地图。

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

来自documentation

  

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

答案 1 :(得分:2)

而不是style使用css,如下所示:

$("<div />", {
    id: "test",
    name: "test",
    "class": "test-class", //patrick's right, IE specifically doesn't like class
    css: {
        width: "100px",
        height: "100px",
        "background-color": "#fff"
    }
});

You can give it a try here,还要注意background-color(因为它有短划线)需要引号,或backgroundColor。其他特殊属性以这种方式映射,valcsshtmltextdatawidthheightoffset are treated special here

答案 2 :(得分:2)

另一个解决方案(在单独的答案中,可以单独向上或向下投票我的任何一种解决方案)只是在之后添加对.css()的调用:

$('<div>',
{
    id: 'test',
    name: 'test',
    class: 'test-class'
}).css(
{
    width: '100px',
    height: '100px',
    backgroundColor: '#fff'
});

答案 3 :(得分:0)

你总是可以编写自己的帮助方法,让你做到

$('<div>',
{
    id: 'test',
    name: 'test',
    class: 'test-class',
    style: $.objectToCss(
    {
        width: '100px',
        height: '100px',
        background-color: '#fff'
    })
}

这种帮助方法的完全未经测试的版本可能如下所示:

$.objectToCss = function(obj) {
    var css;
    $.each(obj, function(name, value) {
        css += name + ': ' + value + ';';
    });
    return css;
};
相关问题