我有一个动态生成的页面,其结构如下:
<div class="list-item">
<div class="year">xxx1</div>
<div class="other-data">xxx1</div>
<div class="item-title">Title 1</div>
<div class="item-information"></div>
</div>
<div class="list-item">
<div class="year">xxx2</div>
<div class="other-data">xxx2</div>
<div class="item-title">Title 2</div>
<div class="item-information"></div>
</div>
页面上有多个列表项。
在每个列表项中,我需要获取“年份”和“其他数据”并将其从项目标题上方删除并 append 到“项目信息”。
我尝试过以下方法:
$('.year').appendTo('.item-information');
$('.other-data').appendTo('.item-information');
这不能正常工作,因为它基本上需要“year”的所有实例并将其 append 到“item-information” - 因此,如果页面上有 3 个项目,每个项目最终会显示 3 个“year”实例在每个“项目信息”中。
为了解决这个问题,我知道我需要某种语句来选择列表项,在该列表项中查找年份和其他数据,然后在同一列表项中查找项目信息并将其 append 到那里。问题是,我不确定如何构造该语句,我尝试了以下方法,但出现了错误:
$('.list-item').find('.year').appendTo(function({
$(this).find('.item-information');
});
有人可以帮我找到我想做的事情的正确结构吗?
谢谢。
最佳答案
$(".list-item").each(function () { //loop over each list item
myYear= $(".year", this); //get the year of the current list item
$(".item-information", this).append(myYear); //append it to the item information
});
您可以这样做,当然对于每个其他列表项子元素也可以这样做;)
关于jQuery 移动/追加具有相同类名的多个项目,仅在父 div 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26843834/