Jquery 更改克隆元素子元素的 ID 不起作用

Jquery changing ID of cloned element children not working

本文关键字:元素 ID 不起作用 Jquery      更新时间:2023-09-26

我正在尝试克隆一个元素,然后更改其子元素之一的id:

var s = $('.RunWell').clone().wrap('<div>').parent().html();
s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));

但它不起作用,我做错了什么??如何更改克隆元素的子元素的 ID?

你不必去它的html。只需使用克隆的 jQuery 对象。

试试这个

var s = $('.RunWell').clone().wrap('<div>');
s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));

var s = $('.RunWell').clone().wrap('<div>').parent().html();

为变量s分配字符串值。但是你通过对它执行 .find 来假设它是下一行的 jquery 对象。

它应该是

var $s = $('.RunWell').clone().wrap('<div>').parent();
$s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));
//$s is used to denote it as a jquery object to provide more readability to code.