2011-09-13 48 views
0

我已經看到了一些使用JQuery將類添加到動態創建元素的不同方法。JQuery添加類的不同方法

我當我測試了在Fiddle第二種方法我可以看到兩者的Class1和Class2中我最熟悉的

$("<div />").addClass("class1 class2"); 

但是我已經看到了很多的

$("<div />", { 
    class : "class1 class2" 
}); 

應用。

然而,當應用於什麼i'm working on

// this does not work 
var b = $("<div id='tweetBox' />", { 
    class : "triangle-right right" 
}); 

// this works 
var b = $("<div id='tweetBox' />").addClass("triangle-right right"); 

回答

1

你不能混搭。

嘗試:

var b = $("<div />", { 
    id: "tweetBox", 
    class : "triangle-right right" 
}); 
+0

打*我* *。 – Blazemonger

0
// this does not work 
var b = $("<div id='tweetBox' />", { 
    class : "triangle-right right" 
}); 

不起作用,因爲有你正在創建的元素的屬性。

This will work 
var b = $("<div />", { 
    id: 'tweetBox', 
    class : "triangle-right right" 
});