将p-和ul-元素包装在同一容器中 [英] Wrapping p- and ul-elements in the same container

查看:53
本文介绍了将p-和ul-元素包装在同一容器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过JQuery用div-container(class = editable)包装所有p和ul-Elements。同一内容-Container中的所有元素都应该包含在同一个可编辑容器中。

I need to wrap all p and ul-Elements with a div-container (class=editable) via JQuery. All elements in the same "content"-Container should be wrapped in the same editable-container.

所以这个HTML代码......

So this HTML-Code...

<div id="article">
    <p>Lorem ipsum</p>
    <p>Lorem ipsum</p>
    <section class="box_1">
        <header class="trigger"><h2>Title</h2></header>
        <div class="content">
            <ul>
                <li>Lorem</li>
                <li>ipsum</li>
            </ul>
            <p>Lorem ipsum</p>
        </div>
    </section>
    <section class="box_1">
        <header class="trigger"><h2>Title</h2></header>
        <div class="content">
            <p>Lorem ipsum</p>
            <p>Lorem ipsum</p>
        </div>
    </section>
</div>

...应该成为这个......

...should become this...

<div id="article">
    <div class="editable">
        <p>Lorem ipsum</p>
        <p>Lorem ipsum</p>
    </div>
    <section class="box_1">
        <header class="trigger"><h2>Title</h2></header>
        <div class="content">
            <div class="editable"> <!-- this part doesn't work right now -->
                <ul>
                    <li>Lorem</li>
                    <li>ipsum</li>
                </ul>
                <p>Lorem ipsum</p>
            </div> <!-- this part doesn't work right now -->
        </div>
    </section>
    <section class="box_1">
        <header class="trigger"><h2>Title</h2></header>
        <div class="content">
            <div class="editable">
                <p>Lorem ipsum</p>
                <p>Lorem ipsum</p>
            </div>
        </div>
    </section>
</div>

我正在使用此代码:

$('.content > p, #article > p').each(function () {
    if (!$(this).closest('.editable').length) $(this).nextUntil('div, section').addBack().wrapAll("<div class='editable' />");
});

...这适用于每个p元素。但是我该如何修改它,所以ul-Elements(带有内部li-Elements)的处理方式就像p元素一样?它们也应该被包装。

...and this works fine for every p-element. But how do I have to modify that, so the ul-Elements (with the inner li-Elements) are handled like a p-element? They should also be wrapped.

推荐答案

你可以简单地遍历元素并包装它们的 p ul 子女:

You can simply iterate through the elements and wrap their p and ul children:

$('#article, .content').each(function() {
    $(this).children('p, ul').wrapAll("<div class='editable' />");
});

http://jsfiddle.net/7Le9r/

这篇关于将p-和ul-元素包装在同一容器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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