gpt4 book ai didi

jQuery - 移动相关元素

转载 作者:行者123 更新时间:2023-12-01 03:23:35 25 4
gpt4 key购买 nike

在页面加载时,我想用 div 包裹标题范围并将其移动到相关主体 div 的前面。即,将hApplicant1 span移动到tabApplicant1 div的前面,等等

如何编写 jQuery 来完成此任务?谢谢!

给定:

<div>
<div id="header">
<span id="hDummy"></span>
<span id="hApplicant1">James Smith</span>
<span id="hApplicant2">John Doe</span>
<span id="hApplicant3"></span>
<span id="hApplicant4"></span>
</div>
<div id="body">
<div id="tabApplicant1">...</div>
<div id="tabApplicant2">...</div>
</div>
</div>
<div>
<div id="header2">
<span id="h2Dummy"></span>
<span id="h2Applicant1">Black Smith</span>
<span id="h2Applicant2">Shoe Maker</span>
<span id="h2Applicant3"></span>
<span id="h2Applicant4"></span>
</div>
<div id="body2">
<div id="tab2Applicant1">...</div>
<div id="tab2Applicant2">...</div>
</div>
</div>

结果应该是这样的:

<div>
<div id="header">
<span id="hDummy"></span>
<span id="hApplicant3"></span>
<span id="hApplicant4"></span>
</div>
<div id="body">
<div><span id="hApplicant1">James Smith</span></div>
<div id="tabApplicant1">...</div>
<div><span id="hApplicant2">John Doe</span><div>
<div id="tabApplicant2">...</div>
</div>
</div>
<div>
<div id="header2">
<span id="h2Dummy"></span>
<span id="h2Applicant3"></span>
<span id="h2Applicant4"></span>
</div>
<div id="body2">
<div><span id="h2Applicant1">Black Smith</span></div>
<div id="tab2Applicant1">...</div>
<div><span id="h2Applicant2">Shoe Maker</span><div>
<div id="tab2Applicant2">...</div>
</div>
</div>

最佳答案

var $bodyDiv = $('#body');

$('#header span[id^=hApplicant]').each(function(){
$bodyDiv.find('div[id=' + $(this).attr('id').replace('h', 'tab') + ']').before( $(this).wrap('<div />').parent() );
});

这是 fiddle :http://jsfiddle.net/Hw2Gz/

这可以进一步简化(和优化),但它应该让您走上正确的轨道。

<小时/>

编辑:

这可以重复:

var $bodyDiv = $('#body'),
$bodyDiv2 = $('#body2');

$('#header span[id^=hApplicant]').each(function(){
$bodyDiv.find('div[id=' + $(this).attr('id').replace('h', 'tab') + ']').before( $(this).wrap('<div />').parent() );
});

$('#header2 span[id^=h2Applicant]').each(function(){
$bodyDiv2.find('div[id=' + $(this).attr('id').replace('h', 'tab') + ']').before( $(this).wrap('<div />').parent() );
});

http://jsfiddle.net/Hw2Gz/1/

关于jQuery - 移动相关元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7353382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com