2012-08-15 76 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); 

这应该工作,它可以节省你不得不连接选择器值。