如何使用 jQuery 为孩子附加 id 属性

Luk*_*kas 0 javascript jquery parent-child attr

我有这个标记:

<div>
  <span id="01">
</div>
<div>
  <span id="02">
</div>
Run Code Online (Sandbox Code Playgroud)

我需要div通过他们的跨度孩子为元素添加一些 id ,我用 jquery 尝试但有些东西磨损了...

$('div').each(function(){
    $(this).attr('id', $(this).find('span').attr('id'));
})
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。

lee*_*ell 5

你的例子似乎工作正常。但是 id 应该是唯一的,所以我建议:

$('div').each(function(){
    $(this).attr('id', 'div-' + $(this).find('span').attr('id'));
});
Run Code Online (Sandbox Code Playgroud)

我还假设您在页面加载事件之后运行您的示例。