开发者

JQuery, cannot change the ID of a cloned element?

Is there an issue with updating ID's of cloned elements? I think my syntax is correct here but it's not updating.

function addQuestion(){
// Clone the first question Container and give it a new ID
$('#questionContainer0').clone().attr('id','questionContainer'+currentQuestion).appendTo('#questionArea');


// Assign the new ID to the text area field (This is not working)
$('#question0开发者_Go百科').attr('id','asdasd');
var test = $('#question0').attr('id');
alert(test);
}

Question0 is a child element (textarea) of the original cloned questionContainer0 (div)


change

$('#question0').attr('id','asdasd');

to

$('#question0', '#questionContainer'+currentQuestion).attr('id','asdasd');

this would restrict your search inside the cloned elements only.

And to be more sure, you should do that before even appending the cloned elements in the DOM, since IDs are supposed to be unique in the DOM.

function addQuestion(){
// Clone the first question Container and give it a new ID
var newElement = $('#questionContainer0').clone().attr('id','questionContainer'+currentQuestion);
newElement.find('#question0').attr('id','asdasd');
newElement.appendTo('#questionArea');

}


You're successfully changing the id attribute here:

$('#question0').attr('id','asdasd');

But then you try to access the element with the original (no longer existing) id in the next line:

var test = $('#question0').attr('id');

Could that be the problem?


Is your alert giving you undefined? This would be because you're selecting an element by Id, changing that Id, then using jQuery to look up the element by the old id (which returns an empty result set). alerting the id of the first element in an empty result set will yield undefined.


You change the id ($('#question0').attr('id','asdasd')), and then get the element with the old id ($('#question0').attr('id')), which no longer exists.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜