2012-08-15 74 views
0

我試圖創建一個元素類名的ID元素基於元素ID ...如何創建類名

我的代碼

//$elementClass has no id attrbute 

      elementID=$elementClass.attr('class'); 

       $elementClass.first().attr('id',elementID); 
       $element=$(elementID);    
       console.log($element); 

//the console.log doesn't output anything.... 

誰能幫我一下嗎?非常感謝。

+1

先試一下'console.log(elementID)',看看你得到了什麼......也許你可以自己弄明白嗎? – ahren 2012-08-15 00:13:24

回答

3

除非你的班級裏有#這個字符,否則你得到的只是班級名稱的值。如果要選擇具有該ID的元素,則需要將#字符添加到選擇器。

$element=$('#' + elementID); 

但是,看到你正在執行first()已經獲得感興趣的元素,您不妨緩存該對象在這一點上,並從那裏上使用它。

// Get the id value from the class name 
elementID = $elementClass.attr('class'); 

// Create a jQuery object of the element I want to update 
var $element = $elementClass.first(); 

// Update the element 
$element.attr('id',elementID); 

// Show the results in the console 
console.log($element); 

這應該工作,它可以節省你不得不連接選擇器值。