JQuery,ID和Name属性不更新

时间:2011-07-06 07:59:07

标签: jquery

有关为什么ID和名称未在此处更新的任何想法?

function addQuestion(){
var currentQuestion = $(".questionContainer").size(); //Number of questionContainers
var $newElement = window.$pQuestion.clone().attr('id','questionContainer'+currentQuestion);
$newElement.children('#question0').attr('id','question'+currentQuestion).attr('name','quest ion'+currentQuestion);

//Update the answerContainer div id.
$newElement.children('#answerContainer0').attr('id','answerContainer'+currentQuestion);

//Update the first answer id and name
var answerId = 'question'+currentQuestion+'-answer1';
$newElement.children('#question0-answer1').attr("id",answerId).attr("name",answerId);
$newElement.appendTo('#questionArea');
}

最后几行是问题所在。这应该更新为“question1-answer1”我已经验证了answerId的值是正确的,似乎没有应用于ID和名称。

如果您想了解更多情况,请与我们联系。

2 个答案:

答案 0 :(得分:1)

#question0-answer1是DOM中.questionContainer的直接孩子吗?

或者它可能嵌套得更深?在这种情况下,您需要使用

$newElement.find('#question0-answer1').attr("id",answerId).attr("name",answerId);

<强>更新

看到发布的代码,确实你的元素不是孩子而是后代,所以请使用上面的建议。

答案 1 :(得分:0)

尝试插入这几个提醒

//Update the first answer id and name
var answerId = 'question'+currentQuestion+'-answer1';

// this should display the expected id
alert(answerId);

// the display of this should be greater than zero else 
// #question0-answer1 is not an immediate child of $newElement

alert($newElement.children('#question0-answer1').length());

$newElement.children('#question0-answer1').attr("id",answerId).attr("name",answerId);
$newElement.appendTo('#questionArea');

我建议您使用.find()而不是.children()

$newElement.find('#question0-answer1').blah.blah;