在每5个项目后加载div及其内容

时间:2015-09-08 17:28:34

标签: javascript jquery html5 smarty3

我在这个链接上有输出代码的智能模板:

My other Question in Stackoverflow

我的问题是那里提供的代码没有:重复插入的HTML每个5个元素......

有人可以通过提供解决方案帮助我能够在每个5个元素之后插入其他潜水内容以使最终输出看起来像这样:

    <section id="listings" class="list clearfix">
<article class="item">
<article class="item">
<article class="item">
<article class="item">
<article class="item">

**OTHER DIV BY CLASS OR ID**

<article class="item">
<article class="item">
<article class="item">
<article class="item">
<article class="item">


**OTHER DIV BY CLASS OR ID**

<article class="item">
<article class="item">
<article class="item">
<article class="item">
<article class="item">


**OTHER DIV BY CLASS OR ID**

<article class="item">
<article class="item">
<article class="item">
<article class="item">
<article class="item">
</section>

2 个答案:

答案 0 :(得分:4)

使用nth-child选择器和after()

$('.item:nth-child(5n)').after('<article>inserted after 5th</article>');

$('.item:nth-child(5n)').after('<article>inserted after 5th</article>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section id="listings" class="list clearfix">
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>



  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>




  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>



  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
  <article class="item">test</article>
</section>

答案 1 :(得分:0)

建议

  

我可以添加div,其内容有类或ID吗?比如我   已经有一个带横幅的div,我需要用你的代码重复它

您可以在页面上将其渲染为类似未知类型的脚本元素(浏览器将忽略它),如下所示:

<script type="template/banner" id="div-banner">
    <div class="banner">
      <img src=".../NNNxNNN/banner.png" />
    </div>
</script>

然后像建议的那样插入它:

$('.item:nth-child(5n)').after($("#div-banner").html());

它将使您的JavaScript更清洁,并且不会使用垃圾变量污染全局范围。