代码之家  ›  专栏  ›  技术社区  ›  cllpse

使用对象文字创建具有属性的元素

  •  2
  • cllpse  · 技术社区  · 14 年前

    $("<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 回复  |  直到 14 年前
        1
  •  10
  •   Andy E    14 年前

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

    documentation

    此外,可以传入任何事件类型,并可以调用以下jQuery方法:val, 、html、文本、数据、宽度、高度或偏移量。

        2
  •  2
  •   Tomas Aschan    14 年前

    另一个解决方案(在一个单独的答案中,可以分别投票给我的解决方案中的任何一个)是只需给 .css() 之后:

    $('<div>',
    {
        id: 'test',
        name: 'test',
        class: 'test-class'
    }).css(
    {
        width: '100px',
        height: '100px',
        backgroundColor: '#fff'
    });
    
        3
  •  2
  •   Nick Craver    14 年前

    而不是 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 . 其他特殊属性是这样映射的, val , css格式 , html , text , data , width , height offset are treated special here .

        4
  •  0
  •   Tomas Aschan    14 年前

    $('<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;
    };