javascript - 使用 jQuery 在 n 个元素后插入一个 div

标签 javascript jquery insert append

如何插入div.test每n个div之后s 并检查 div.test 是否已存在于所需/目标位置以防止插入重复项?

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

使用类似 $.InsertEveryNItems('div.container', '<div class="added"></div>', 3); 的内容最终结果如下:

<div>1</div>
<div>2</div>
<div>3</div>
<div class="test"></div
<div>4</div>
<div>5</div>

我试过div:eq(3)div:nth-child(3n) ,但新的时候都不起作用 div s 动态添加到页面。

http://jsfiddle.net/Yg22b/7/ @KevinB 的效果很好,但它删除了 div.test来自 DOM 的元素,并在每次动态添加更多元素时重新插入它 div s。如果有办法避免这种情况就好了?

最佳答案

这是一个函数,它将在指定的代码后添加所需的 html,它还将跟踪您之前的索引调用,并且不允许您更新相同的第 n 个选择器

var addNth = (function () {
    var len, i = 0, className, prevIndexes = [];

    function isNew (el) {
         return el.hasClass(className); // removed unnecessary parenthesis
    }

    return function (selector, html, nth, className ) {
        var els = $( selector );
        className = className || 'test';

        if ( $.inArray(nth, prevIndexes) === -1 ) {
            prevIndexes.push(nth);

            $.each(els, function( index, el ) {
                el = $(el);
                if ( (i % nth) === 0 && i !== 0 ) {
                    if ( ! isNew(el) ) {
                        el.before( html );
                    }
                }
                i++;
            });
            i = 0;
        }
    }
})();

addNth('div','<p class="test">Test</p>',3);
addNth('div','<p class="test">Test</p>',3); // won't add content

在这里摆弄::http://jsfiddle.net/kkemple/YJ3Qn/3/

关于javascript - 使用 jQuery 在 n 个元素后插入一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478661/

相关文章:

javascript - 在 selectize.js 中禁用焦点下拉菜单

jquery - IE 的 CSS3 动画旋转器解决方法

c++ - 为什么 std::vector::insert 是一个带有空初始化列表的无操作?

sql - 基于SELECT结果的SQL INSERT

php - PDO 将信息从一个数据库插入到另一个数据库

javascript - 无法在 componentWillMount() 中多次调用 setState,解决方法是什么 React Native

javascript - Chartjs 工具提示 anchor 在条形图上的位置

javascript - 与Redis缓存的连接失败

javascript - 动画队列

javascript - 返回 JS 对象但 responseText 不起作用