0

要素クラス名の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.... 

誰かがそれについて私を助けることができますか?どうもありがとう。

4

1 に答える 1

3

Unless your class has the # character in it, all you get is the class name value. You need to add the # character to your selector if you want to select the element with that id.

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

However, seeing you are executing first() already to get the element of interest you might as well cache that object at that point and use it from there on.

// 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);

That should work too and it saves you having to concatenate selector values.

于 2012-08-15T00:14:54.087 に答える