Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JQuery,无法更改克隆元素的ID?_Jquery - Fatal编程技术网

JQuery,无法更改克隆元素的ID?

JQuery,无法更改克隆元素的ID?,jquery,Jquery,更新克隆元素的ID是否存在问题?我认为我的语法在这里是正确的,但它没有更新 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

更新克隆元素的ID是否存在问题?我认为我的语法在这里是正确的,但它没有更新

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').attr('id','asdasd');
var test = $('#question0').attr('id');
alert(test);
}

Question0是原始克隆questionContainer0(div)的子元素(textarea)

您的
警报是否为您提供
未定义的
?这是因为您正在按Id选择元素,更改该Id,然后使用jQuery按旧的
Id
(返回空结果集)查找元素<代码>警报
对空结果集中第一个元素的
id
进行加密将产生
未定义的

您在此处成功更改了
id
属性:

$('#question0').attr('id','asdasd');
但随后您尝试使用下一行中的原始(不再存在)id访问元素:

var test = $('#question0').attr('id');
这可能是问题所在吗?

改变

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

这将限制您仅在克隆元素内进行搜索

更确切地说,您应该在DOM中添加克隆元素之前执行此操作,因为ID在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');

}

您可以更改id($('question0').attr('id','asdasd')),然后获取旧id($('question0').attr('id'))不再存在的元素。

确实如此。我需要重新考虑这一点,因为我只需要更新新克隆元素的ID,所以我认为我需要导航到父克隆元素的子元素,并以这种方式进行更新。发现这篇2009年的帖子与我想做的类似:嗨,加比,谢谢,你展示的语法允许我将父元素指定为选择器中的第二个参数吗?嗯,仍然没有骰子-发布时的表单字段都命名为question0。我验证了questionContainer ID实际上发生了变化,但是问题0没有。我们确定jQuery每次都在克隆question0的ID吗?@bob,您的元素是否也有name属性?(还有一个值为question0)您也需要更改,因为提交的是
名称
。加布,谢谢-盯着它看了一段时间后,我意识到我缺少了名称属性。。啊!
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');

}