如何使用javascript或MooTools在特定DIV之后或之前包装所有DIV?

时间:2014-08-09 05:56:21

标签: javascript html css mootools

我想要做的是尝试在某些特定DIV之后或之前包装所有DIV。

这是代码:

<div class="heading">Heading one</div>
<div>question one</div>
<div>question two</div>
<div>question three</div>
<div class="heading">Heading two</div>
<div>question one</div>
<div>question two</div>
<div>question three</div>
<div>question four</div>
<div>question five</div>
<div>question six</div>
<div class="heading">Heading three</div>
<div>question one</div>
<div>question two</div>

所以这些标题DIV中的问题我想动态地包装它们,所以如果任何标题的问题或多或少会自动换行到另一个div中,并将id或类分配给它们来显示和隐藏。

想要使用JavaScript或mootools动态地执行此操作:

请记住,当用户从管理面板添加每个标题时,问题可能会有所不同。

编辑:还请记住,标题也可能有所不同,可能会有更多标题可由用户添加,每个标题都可能包含问题。

<div class="heading">Heading one</div>
<div id='one'>
    <div>question one</div>
    <div>question two</div>
    <div>question three</div>
</div>
<div class="heading">Heading two</div>
<div id='two'>
    <div>question one</div>
    <div>question two</div>
    <div>question three</div>
    <div>question four</div>
    <div>question five</div>
    <div>question six</div>
</div>
<div class="heading">Heading three</div>
<div id='three'>
    <div>question one</div>
    <div>question two</div>
</div>

如果您认为评论中的问题不好,请告诉我,如果您评价为差,我将无法提出更多问题。

感谢。

3 个答案:

答案 0 :(得分:1)

这应该这样做:

var newParent, id = 1;
$$('div').each(function (element) {
    if (element.hasClass('heading')) {
        newParent = new Element('div[id=heading_' + id + ']').inject(element, 'after');
        id++;
    } else {
        newParent.wraps(element);
    }
});

示例:jsFiddle

或者没有全局变量:

$$('div').each(function (element) {
    if (element.hasClass('heading')) {
        var id = $$('div[id^=heading_').length + 1;
        var newParent = new Element('div[id=heading_' + id + ']').inject(element, 'after');
    } else {
        element.getPrevious().wraps(element);
    }
});

示例:jsFiddle

.wraps() 方法是关键所在。

答案 1 :(得分:0)

<强> Demo

JS

$('.heading + div').each(function () {
    $(this).nextUntil(".heading").andSelf().wrapAll('<div class="content" />');
});

这里有不同的ID

<强> Demo

JS

var ID = 0;
$('.heading + div').each(function () {
    ID++;
    $(this).nextUntil(".heading").andSelf().wrapAll('<div class="content" />').attr('id', 'id' + ID);
});

<强>

Final Demo

JS

$('.heading + div').each(function (index, element) {
    $(this).nextUntil(".heading").andSelf().wrapAll('<div class="content" />');
    $(element).parent().attr('id', 'id' + index);
});

我正在使用索引和元素,因此id计数从0开始

不影响最后一个

<强>

Demo not to effect last

JS

$('.heading:not(:last) + div').each(function (index, element) {
    $(this).nextUntil(".heading").andSelf().wrapAll('<div class="content" />');
    $(element).parent().attr('id', 'id' + index);
});

答案 2 :(得分:0)

将已经提到的jquery解决方案应用于mootools,您将使用“GetUntil”方法:http://mootools.net/forge/p/element_getuntil。然后使用换行包装:http://mootools.net/docs/core/Element/Element#Element:wraps