使用属性创建jQuery对象的首选方法是什么?

时间:2022-01-29 19:37:53

When creating jQuery objects I've used the following syntax lately, as described here:

在创建jQuery对象时,我最近使用了以下语法:

var $el = $('<div/>', {
   class: 'class-1 class-2'
});

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Safari 5.0.5在我使用上述结构时出现语法错误。

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

删除第二个参数并添加带有addClass的类可以消除错误,但是看起来不太好。

How do you create your objects? I tried with attr({class: 'class-1'}), as well, but received the same syntax error.

如何创建对象?我尝试了attr({class: ' class1 '}),但也收到了相同的语法错误。

4 个解决方案

#1


7  

You can't use class; it's a reserved word.

你不能使用类;这是一个保留字。

Use className instead:

使用类名:

var $el = $('<div/>', {
   className: 'class-1 class-2'
});

#2


3  

Make the attribute name a string:

将属性名设置为字符串:

var $el = $('<div/>', {
    'class': 'class-1 class-2'
});

JSFiddle Example

JSFiddle例子

#3


1  

Since class is a reserved word, you need to put it in quotes.

因为类是一个保留词,所以需要把它放在引号中。

var $el = $('<div/>', {
   "class": 'class-1 class-2'
});

#4


1  

You get an error as class is a reserved keyword. You can use a string as identifier when a property name is a reserved keyword:

你会得到一个错误,因为类是一个保留的关键字。当属性名称为保留关键字时,可以使用字符串作为标识符:

var $el = $('<div/>', {
   'class': 'class-1 class-2'
});

#1


7  

You can't use class; it's a reserved word.

你不能使用类;这是一个保留字。

Use className instead:

使用类名:

var $el = $('<div/>', {
   className: 'class-1 class-2'
});

#2


3  

Make the attribute name a string:

将属性名设置为字符串:

var $el = $('<div/>', {
    'class': 'class-1 class-2'
});

JSFiddle Example

JSFiddle例子

#3


1  

Since class is a reserved word, you need to put it in quotes.

因为类是一个保留词,所以需要把它放在引号中。

var $el = $('<div/>', {
   "class": 'class-1 class-2'
});

#4


1  

You get an error as class is a reserved keyword. You can use a string as identifier when a property name is a reserved keyword:

你会得到一个错误,因为类是一个保留的关键字。当属性名称为保留关键字时,可以使用字符串作为标识符:

var $el = $('<div/>', {
   'class': 'class-1 class-2'
});