2013-08-29 35 views
0

我有這個jQuery代碼作爲一個循環的一部分,爲每個div生成div和設置屬性。jQuery - 如何設置特定格式的標題屬性

var names = $('<div/>', { 
     id: load1array[j], 
    'class': 'bold', 
    html: load1array[j] 
     }); 

我想爲每個div添加一個title屬性,但我忘了語法。我已經嘗試了下面的代碼,但它們似乎不是正確的語法。

var names = $('<div/>', { 
     id: load1array[j], 
    'class': 'bold', 

//attr:('title','text here'),   
//title:'text here' ,  
//'title':'text here' , 

     html: load1array[j] 
     })//.attr("title", "text here"); 

TIA

編輯:

我也看到這裏的答案Creating a div element in jQuery,這表明,包括標題的代碼屬性

jQuery('<div/>', { 
    id: 'foo', 
    href: 'http://google.com', 
    title: 'Become a Googler', 
    rel: 'external', 
    text: 'Go to Google!' 
}).appendTo('#mySelector'); 

但它並沒有爲我工作已經嘗試過,根據答案的鏈接,標題屬性可能不適用於<div>標籤,而是<a>標籤。

+0

你確定 '標題': '這裏的文字',沒有工作?我99%確定這是正確的。 – htxryan

+0

[jQuery創建具有屬性差異的元素]的可能重複(http://stackoverflow.com/questions/9898442/jquery-create-element-with-attribute-differences) – Fresheyeball

+1

似乎很好http://jsfiddle.net/ arunpjohny/brFyZ/1/ –

回答

1

試試這個:

var names = $('<div/>', { 
    id: load1array[j], 
'class': 'bold', 
html: load1array[j] 
    }); 

names.attr("title", "text here"); 
+0

感謝ivowiblo,此代碼按預期工作。但我不明白爲什麼當我將它鏈接到聲明的結尾時它不起作用。 – Jamex

相關問題