在页面加载时,我想用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>
答案 0 :(得分:3)
var $bodyDiv = $('#body');
$('#header span[id^=hApplicant]').each(function(){
$bodyDiv.find('div[id=' + $(this).attr('id').replace('h', 'tab') + ']').before( $(this).wrap('<div />').parent() );
});
这是小提琴: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() );
});
答案 1 :(得分:1)
$('#header span').each(function() {
var that = $(this);
var thatId = that.attr('id');
var bodyDiv = $('#body #' + thatId.replace('h', 'tab'));
if (bodyDiv.length)
that.insertBefore(bodyDiv).wrap('<div/>');
});