首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery动态级AppendTo

jQuery动态级AppendTo
EN

Stack Overflow用户
提问于 2014-07-01 07:02:51
回答 8查看 1.7K关注 0票数 4

我有以下代码:

HTML:

代码语言:javascript
复制
<ul id="main-menu">
    <li><a href="#page-1" class="slide-item selected">page 1</a></li>
    <li><a href="#page-2" class="slide-item">page 2</a></li>
    <li><a href="#page-3" class="slide-item">page 3</a></li>
    <li><a href="#page-4" class="slide-item">page 4</a></li>
</ul>

<div class="test">
    <div id="page-1" class="page">
    <div class="page-container">
        <h3>page 1</h3>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequatur deleniti eum illo itaque
            iusto officia soluta, veritatis? Ab aliquam autem cum doloribus eaque eum in itaque natus rem, vero.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequatur deleniti eum illo itaque
            iusto officia soluta, veritatis? Ab aliquam autem cum doloribus eaque eum in itaque natus rem, vero.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequatur deleniti eum illo itaque
            iusto officia soluta, veritatis? Ab aliquam autem cum doloribus eaque eum in itaque natus rem, vero.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequatur deleniti eum illo itaque
        </p>
        </div>
    </div>
</div>

JQUERY:

代码语言:javascript
复制
    $.fn.insertAt = function(index, elements){
    var children = this.children();
    if(index >= children.size()){
        console.log(index+'>='+children.size());
        this.append(elements);
        return this;
    }
    var before = children.eq(index);
    $(elements).insertBefore(before);
    return this;
}; //http://upshots.org/javascript/jquery-insert-element-at-index

jQuery('.slide-item').on('click', function(){
        var item = jQuery('a[href="'+jQuery(this).attr('href')+'"]').parent();
        var index = jQuery("ul li").index(item);
        //console.log(index);
        var target = jQuery(this).attr('href').substr(1);

        if(jQuery(jQuery(this).attr('href')).length){
            console.log('loaded');
        }else {
            jQuery.get("pages/"+target+".html", function(data){
                jQuery('.test').insertAt(index, data);
            });
        }

        return false;
    });

基本上,正如您可能看到的,根据单击它加载页面的链接,现在我的实际问题是:

有什么办法维持他们的秩序吗?

例如,如果我按这个顺序点击链接1,4,2,3,那么这就是页面被附加到页面的顺序:

代码语言:javascript
复制
<div id="page-1" class="page">
<div id="page-4" class="page">
<div id="page-2" class="page">
<div id="page-3" class="page">

但是,我需要它独立于你点击链接的顺序。因此,例如,如果我单击1,3,2,4,然后我需要按顺序追加页面(1,2,3,4):

代码语言:javascript
复制
<div id="page-1" class="page">
<div id="page-2" class="page">
<div id="page-3" class="page">
<div id="page-4" class="page">

最近我尝试通过索引来完成它,方法是获取单击项li的索引,然后尝试使用我找到的insertAt函数在该索引处插入div。但是它并不完全起作用,例如,如果我单击4,那么3将被追加到4后面。

任何帮助都将不胜感激。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2014-07-10 08:59:31

我建议您通过为每个页面创建空占位符DIVs来简化整个系统。这样,命令就已经到位。

JSFiddle:http://jsfiddle.net/TrueBlueAussie/R2T4Z/4/

代码语言:javascript
复制
// Use wrapped DOM ready event to provide local $ for jQuery
jQuery(function ($) {
    $('.slide-item').on('click', function () {
        var $link = $(this);
        var target = $link.attr('href').substr(1);

        // If the div has any content it is "loaded" (if you know the page has child elements use children().length as it will be faster)
        if ($('#' + target).html().length) {
            console.log('loaded');
        } else {
            // Dummy test code - REMOVE THIS
            $('#' + target).html("I AM LOADED:" + target);
            // End dummy test code
            $.get("pages/" + target + ".html", function (data) {
                $('#' + target).html(data);
            });
        }

        return false;
    }).each(function (index) {
        // create an empty placeholder DIV (in order) with unique matching id for each new entry
        var $link = $(this);
        var id = $link.attr("href").substr(1);
        // If page not already present...
        if (!$('#' + id).length) {
            $('.test').append($('<div>').attr("id", id));
        }
    });
});

*注意:jQuery(function ($) {YOU CODE HERE});jQuery(document).ready($){YOUR CODE HERE});的快捷方式,它提供了一个本地范围的$,因此您的jQuery代码更短。

更新:http://jsfiddle.net/TrueBlueAussie/ugZST/12/

经过多次讨论后,需求还需要使用水平滑块。现有的是一次性类型,与动态内容不兼容,因此我也使用了一个slideToPage函数来替换它,该函数使用绝对动画将页面导入或移出视图:

代码语言:javascript
复制
function slideToPage($page){
    var $wrapper = $('.wrapper');
    var width = $wrapper.outerWidth();
    var height = $wrapper.outerWidth();

    // Set size of all children and stop previous animations
    $wrapper.children().css({width: width, height: height}).stop();

    // Find the current page (positioned at 0)
    var $currentpage = $wrapper.find('.currentpage');
    if ($page.is($currentpage)){
        console.log("Stay on current page");
        return;
    }
    console.log("$currentpage.index() " + $currentpage.index());
    console.log("$page.index() " + $page.index());

    // Is the new page index before or after (left or right scroll)
    var slideRight = $page.index() > $currentpage.index();
    var delta = slideRight ? 1 : -1;

    // Position offscreen (to left or right of the screen)
    $page.css({left: delta * width});

    // Animate new panel to positon 0
    $page.animate({left: 0}, 1000).show();

    // Animation old panels offscreen (left or right) then hide
    $currentpage.animate({left: -delta * width}, 1000, function(){
        $currentpage.hide();
    });

    $currentpage.removeClass('currentpage');
    $page.addClass('currentpage');

    // hide all other pages (just to be sure)
    $wrapper.children().not($currentpage).not($page).hide();
}

// Use wrapped DOM ready event to provide local $ for jQuery
jQuery(function ($) {
    $('.scrollitem').on('click', function () {
        var $link = $(this);
        var target = $link.attr('href').substr(1);

        // If the div has any content it is "loaded" (if you know the page has child elements use children().length as it will be faster)
        var $page = $('#' + target);
        var $target = $page.find('.page-container');
        if ($target.html().length) {
            console.log('loaded');
            slideToPage($page);
        } else {
            // Dummy test code - REMOVE THIS
            $target.html("I AM LOADED:" + target + "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequatur deleniti eum illo itaque Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequatur deleniti eum illo itaque Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi consequatur deleniti eum illo itaque");
            slideToPage($page);
            $page.css('display', '');
            // End dummy test code
            $.get("pages/" + target + ".html", function (data) {
                $target.html(data);
                slideToPage($page);
                $page.css('display', '');
            });
        }

        return false;
    }).each(function (index) {
        // create an empty placeholder DIV (in order) with unique matching id for each new entry
        var $link = $(this);
        var id = $link.attr("href").substr(1);
        // If page not already present...
        if (!$('#' + id).length) {
            $('.wrapper').append($('<div class="page"><div class="page-container"></div></div>').attr("id", id).css('display', 'none'));
        }
    });
});
票数 1
EN

Stack Overflow用户

发布于 2014-07-09 23:42:42

您的插入-at功能将无助于您在这里。正如您已经发现的,单击第4页,然后第3页不能正确地排序,因为insert-at函数根据子元素的索引插入dom元素。这意味着,如果您有一个像page3,page5这样的列表,那么在索引n处插入任何后续的页面n都会很明显地失败。

这个问题有很多解决方案,很难确定用例的最佳选择,但一个简单的解决方案是简单地遍历当前列表,直到第n个索引的页码大于n,然后将其插入n。在计算机科学中,我们称之为在线插入排序。你可以在这里读到:排序

下面是一个演示:

代码语言:javascript
复制
$.fn.insertAt = function(index, elements){
    var children = this.children();
    if(index >= children.size()){
        console.log(index+'>='+children.size());
        this.append(elements);
        return this;
    }
    var before = children.eq(index);
    $(elements).insertBefore(before);
    return this;
}; //http://upshots.org/javascript/jquery-insert-element-at-index

jQuery('.slide-item').on('click', function(){
    var item = jQuery('a[href="'+jQuery(this).attr('href')+'"]').parent();
    var index = jQuery("ul li").index(item);
    //console.log(index);
    var target = jQuery(this).attr('href').substr(1);

    if(jQuery(jQuery(this).attr('href')).length){
        console.log('loaded');
    }else {
        //jQuery.get("pages/"+target+".html", function(data){
        //    jQuery('.test').insertAt(index, data);
        //});

        // the insert page number happens to be the index
        var data = '<div id="' + target + '" class="page">' + target + ' content</div>';
        var toInsertPageNumber = index;
        var didInsert = false;
        jQuery('.test').children().each(function(k, v) {
            var currentPageNumber = parseInt($(v).attr('id').replace('page-', ''), 10);

            if (currentPageNumber > index) {
                jQuery('.test').insertAt(k, data);      
                didInsert = true;
                return false;
            }
        });

        // if we didn't insert anything, then it goes to the end of the list.
        if (!didInsert) {
            jQuery('.test').append(data);
        }
    }

    return false;
});

下面是包含上述代码的小提琴:http://jsfiddle.net/aDtV5/

票数 0
EN

Stack Overflow用户

发布于 2014-07-11 16:31:47

下面是一个可以发挥作用的函数:

代码语言:javascript
复制
//check by comparing order number
function insert(page){
    //extract order number from element to be inserted
    var placeId = parseInt($(page).attr('id').substr($(page).attr('id').length - 1));
    //loop through each existing page
    $('.page').each(function(){
        //extract order number of current loop iteration
        var id = parseInt($(this).attr("id"));
        //if currently existing item has higher ID than the one to be inserted
        //insert new page before(this works because we can assume order)
        if(id > placeId){
            $([NEW_PAGE]).insertBefore($(this));
            return;
        }
        //in case your trying to load an existing page
        if(id === placeId){return;}
    });
    //page to be loaded is bigger than any already loaded
    $([NEW_PAGE]).insertAfter($('.page').last());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24504250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档