翻转第二个div和第三个div

时间:2014-09-12 06:39:02

标签: javascript jquery

我有四个div,我的查询是我想要替换第二个div和第三个div的顺序,输出应该以这种方式来代替1324而不是1234

<div class="bar">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>
$(document).ready(function() {
    reverseChildren($('.bar'));
    if (document.body.offsetWidth < 600) {  
        function reverseChildren($parent) {
            var listItems = $parent.children('div');
            console.log(listItems);
            $parent.append(listItems.get().reverse());
        };
    }
});

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery's before method交换两个元素的位置。

$('.bar div:nth-child(2)').before($('.bar div:nth-child(3)'));

这里使用你的html jsfiddle

此外,如果您尝试在 if语句之外调用该函数,则函数声明不应位于 if语句中。

答案 1 :(得分:0)

首先:你已经在if语句中包装了函数调用,这很奇怪。您应该使用if语句包装函数调用,并使函数调用本身全局可用。

第二:你的功能现在选择所有的孩子并反转它们,而你只想选择你想要反转的两个孩子中的最后一个项目,然后在它像以前一样对之前的兄弟姐妹进行追加:

<强> HTML

<div class="bar">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

<强>的Javascript

function reverseChild($parent, index)
{
    // Retrieve the child item with the supplied (ZERO BASED!) index
    var childItem = $parent.children('div:eq(' + index + ')');

    // Place it in front of it's immedeate previous sibling.
    childItem.prev().before(childItem);
};

$(document).ready(function()
{
    reverseChild($('.bar'), 2);
});

JSFiddle演示:http://jsfiddle.net/mpcowmpb/

  • 请注意:我已经删除了JSFiddle演示中的document.body.offsetWidth检查,因为该演示中的主体不太宽。
相关问题