用jQuery递归更改元素类型,为什么它部分工作? [英] Recursively change element type with jQuery, why it's partially working?

查看:64
本文介绍了用jQuery递归更改元素类型,为什么它部分工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

源节点:

 <div class="tree">
    <div class="item"><!-- replaced OK -->
        <a href class="toggle">+</a>
        <a href class="name">Name</a>
        <div class="collapse">
            <div class="item"><!-- this wouldn't be replaced ?! --></div>
        </div>
    </div>
    <div class="item"></div><!-- replaced OK -->
</div>

我需要克隆此节点,递归地替换每个 < div class =item> with < li class =item> < div class =collapse> with < ul class =collapse>

I need to clone this node and recursively replace each <div class="item"> with <li class="item"> and <div class="collapse"> with <ul class="collapse">.

对于项目,这将仅适用于第一级:

For items, this will work for the first level only:

var $clone = $('.tree').clone(false);

$clone
    .find('.item')
    .replaceWith(function () {
        return $('<li>'+$(this).html()+'</li>');
    });

我的代码有什么问题吗?

Is there anything wrong in my code?

推荐答案

您的替换功能将使用新的html元素替换第一个 .item 内的html。因此, .find()返回的数组中的其他 .item 不再存在。你可以把它放在一个循环中,所以所有的 .item 被替换为 li s:

Your replace with function will replace the html inside the first .item with new html elements. So the other .item in the array returned by .find() does not exist anymore. You can put this in a while loop, so all .items are replaced by lis:

var $items=$clone.find(".item");
while($items.length>0){
    $items.replaceWith(function () {
        return $('<li>'+$(this).html()+'</li>');
    });
    $items=$clone.find(".item");
}

JSFiddle: http://jsfiddle.net/j14f0bx9/

JSFiddle: http://jsfiddle.net/j14f0bx9/

这篇关于用jQuery递归更改元素类型,为什么它部分工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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