2010-08-06 65 views
2

从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

我知道这已经超出了点的问题,但我认为'className'是必需的,而不是'class',因为'class'是一个保留字。 – user113716 2010-08-06 12:21:52

+0

@patrick - +1 - 你是对的我倾向于忘记它的IE特别不喜欢它,它需要引号或className – 2010-08-06 12:23:20

+0

@patrick:包装类的字符串也可以,例如, ''class“:”test-class“'。 jQuery预计任何可以与* attr()*函数一起使用的东西,所以它与* attr(“class”,“...”)*是同义的。 – 2010-08-06 12:31:24

回答

10

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

documentation

此外,任何事件类型可以传递的,并且下面的jQuery方法可以被称为:缬氨酸,CSS,HTML,文本,数据,宽度,高度或偏移量。

+2

+1使用已经内置的东西。 – 2010-08-06 12:18:22

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; 
}; 
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。其他特殊属性映射这种方式,valcsshtmltextdatawidthheightoffsetare treated special here

2

另一种解决方案(在一个单独的答案,使人们有可能投票的我的解决方案,向上或向下分开的),是只添加一个调用.css()算账:

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