我有一个 div (rateRibbon),我将其添加到随机数量的父 div 中,这将需要在每次父 (rateRibbon) 存在时附加四个子 div。
<div class="ratesListing roomsView">
<div class="rateTypeLineItems"></div>
</div>
<div class="ratesListing roomsView">
<div class="rateTypeLineItems"></div>
</div>
我如何循环遍历直到达到 4,然后停止,而不是向每个父级添加 4 个子级 div?
如何将每个新的 (rateRibbon) 及其 4 个子项附加到每个rateTypeLineItems 上?
这是我的 JQuery:
//prepend rate ribbon at the top of each room rate type
$('.rateTypeLineItems').prepend('<div class="rateRibbon"> <!-- this is a container div --> </div>');
//prepend messaging container into rate ribbon
$('.rateRibbon').prepend('<div class="posMsg"></div><div class="posMsg"></div><div class="posMsg"></div><div class="posMsg"></div>');
//append messaging content every time "rateRibbon" loads
$('.rateRibbon:eq(0)').each(function (i) {
$('.posMsg:eq(0)').append('<h3>Best Price Guarantee</h3><p>Get the lowest price for our hotels. We Guarantee it.</p>');
$('.posMsg:eq(1)').append('<h3>IHG Rewards Club</h3><p>Be part of the world’s best hotel rewards program.</p>');
$('.posMsg:eq(2)').append('<h3>A Guaranteed Room</h3><p>Book directly with IHG to guarantee your room.</p>');
$('.posMsg:eq(3)').append('<h3>No Booking Fees</h3><p>There are no hidden booking fees when booking direct.</p>');
});
还有我的 Fiddle 的链接.
最佳答案
将每条消息存储在一个变量中,并将它们合并到 .rateRibbon 中,这样它就会同时发生,而您不必查询 DOM 太多。
这是 fiddle :http://jsfiddle.net/x8VE5/
修改脚本的关键部分:
var msg1 = '<h3>Best Price Guarantee</h3><p>Get the lowest price for our hotels. We Guarantee it.</p>';
var msg2 = '<h3>IHG Rewards Club</h3><p>Be part of the world’s best hotel rewards program.</p>';
var msg3 = '<h3>A Guaranteed Room</h3><p>Book directly with IHG to guarantee your room.</p>';
var msg4 = '<h3>No Booking Fees</h3><p>There are no hidden booking fees when booking direct.</p>';
//prepend messaging container into rate ribbon
//var rateRibbon = '<div class="posMsg"></div>';
$('.rateRibbon').prepend('<div class="posMsg">'+msg1+'</div><div class="posMsg">'+msg2+'</div><div class="posMsg">'+msg3+'</div><div class="posMsg">'+msg4+'</div>');
关于javascript - 将子 div 附加到父 div 的每个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23618009/