javascript - 将子 div 附加到父 div 的每个实例

标签 javascript jquery

我有一个 div (rateRibbon),我将其添加到随机数量的 div 中,这将需要在每次父 (rateRibbon) 存在时附加四个子 div。

<div class="ratesListing roomsView">
    <div class="rateTypeLineItems"></div>
</div>

<div class="ratesListing roomsView">
    <div class="rateTypeLineItems"></div>
</div>
  1. 我如何循环遍历直到达到 4,然后停止,而不是向每个父级添加 4 个子级 div?

  2. 如何将每个新的 (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/

相关文章:

jquery - jqgrid saveRow 不进行 ajax 调用

javascript - Illustrator JavaScript 只能运行一次 - 不会切换

javascript - 在将 PHP session 传递给 Vue.js 之前,使用 PHP 中的字符串中的空格对 JSON 进行编码

用于在问号之前获取字符串的 Javascript 正则表达式(如果存在)

javascript - 我怎样才能实现这个twbs分页

javascript - 确定页面是否尚未准备好

javascript - 类型错误 : Cannot read property 'publish' of undefined in (ReactJS)

javascript - 为 JavaScript 函数参数转义 PHP 中的引号

javascript - 迭代 js 集合

javascript - Kendo 网格 - 如何在添加/编辑子行(详细信息网格)时访问父行模型