使用insertAfter挂钩元素,但保留在parent-jQuery中 [英] Hook elements with insertAfter, but stay in parent - jQuery

查看:75
本文介绍了使用insertAfter挂钩元素,但保留在parent-jQuery中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery动态更改某些元素的位置。我在这里找到了一些可行的方法: https://stackoverflow.com/a/18593267/1419575 ,但如果索引号高于子计数,元素超出父级。

I'm using jQuery to change certain elements' position dynamically. I found something that works here: https://stackoverflow.com/a/18593267/1419575 , but if the index number is higher than the children count, the element goes out of the parent.

有没有办法让孩子留在父元素中?

Is there a way to make the child stay inside the parent element?

CSS

#hook-header {
    background: #dadada;
    margin: 10px;
    padding: 10px;
}

HTML

<header id="hook-header">
    <div id="ImTheFirstElement"><h1>This is the header hook</h1></div>
</header>

<div id="example-one">01</div>
<div id="example-nintynine">99</div>

jQuery

$(document).ready(function () {
    $('#example-one').appendTo('#hook-header');

    $.fn.appendToIndex=function(to,index){
        if(! to instanceof jQuery){
            to=$(to);
        };
        if(index===0){
            $(this).prependTo(to)
        }else{
            $(this).insertAfter(to.children().eq(index-1));
        }
    };
    $('#ImTheFirstElement').appendToIndex($('#hook-header'),0) 
    $('#example-one').appendToIndex($('#hook-header'),1)  
    $('#example-nintynine').appendToIndex($('#hook-header'),99)
});

DEMO

推荐答案

如果 eq,修改插件以使用最后一个元素(index)不返回元素

$(document).ready(function () {
    $('#example-one').appendTo('#hook-header');

    $.fn.appendToIndex=function(to,index){
        if(! to instanceof jQuery){
            to=$(to);
        };
        if(index===0){
            $(this).prependTo(to)
        }else{
            var el = to.children().eq(index-1);
            el = el.length ? el : to.children().last();
            $(this).insertAfter(el);
        }
    };
    $('#ImTheFirstElement').appendToIndex($('#hook-header'),0) 
    $('#example-one').appendToIndex($('#hook-header'),1)  
    $('#example-nintynine').appendToIndex($('#hook-header'),99)
});

FIDDLE

这篇关于使用insertAfter挂钩元素,但保留在parent-jQuery中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆