2016-08-12 42 views
0

我想(希望)這是一個簡單的。我不完全明白我在這裏做什麼,所以任何幫助都會很棒!jQuery - 重新排序Divs通過函數傳遞Order

我有一個容器內的4個div。我想運行一個函數divOrder(),並通過我希望我的div顯示的順序,如下所示:divOrder(divfour, divTwo, divThree, divOne);這不起作用,我不確定最好的方法是什麼。

HTML:

<div id="container"> 
    <div class="div-1">1</div> 
    <div class="div-2">2</div> 
    <div class="div-3">3</div> 
    <div class="div-4">4</div> 
</div> 

JS:

var divOrder, 
     url = document.location.href; 

divOrder = function (divOne, divTwo, divThree, divFour) { 
    var divOne = $('.div-1'), 
     divTwo = $('.div-2'), 
     divThree = $('.div-3'), 
     divFour = $('.div-4'); 

    $('#container').empty().append(divfour, divTwo, divThree, divOne); 

} 


if (url.indexOf('?test-1') > -1) { 
    divOrder(divfour, divTwo, divThree, divOne); 
} else if (url.indexOf('?test-2') > -1) { 
    divOrder(divThree, divTwo, divFour, divOne); 
} else if (url.indexOf('?test-3') > -1) { 
    divOrder(divOne, divTwo, divfour, divThree); 
} 

小提琴:https://jsfiddle.net/Lvmoyw2u/

感謝您的幫助!

+0

您傳遞是相同的名稱聲明在你divOrder功能頂端的變量參數。通過設置這些值,可以覆蓋每次傳遞的參數。 – beauXjames

+0

這很有道理。我如何將通過的變量與變量關聯起來? – Nick

回答

1

將您的變量聲明移到函數聲明的上方/下方。

我也建議爲函數的參數使用不同的名稱,所以您不要將它們與全局變量混淆。

var divOrder = function(d1, d2, d3, d4) { 
 
    $('#container').empty().append(d1, d2, d3, d4); 
 
} 
 

 
var divOne = $('.div-1'), 
 
    divTwo = $('.div-2'), 
 
    divThree = $('.div-3'), 
 
    divFour = $('.div-4'); 
 

 

 
setInterval(function() { 
 
    divOrder(divOne, divTwo, divThree, divFour); 
 
    setTimeout(function() { 
 
    divOrder(divFour, divTwo, divThree, divOne); 
 
    setTimeout(function() { 
 
     // or without variables: 
 
     divOrder($('.div-3'), $('.div-1'), $('.div-4'), $('.div-2')); 
 
    }, 1000); 
 
    }, 1000); 
 
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div id="container"> 
 
    <div class="div-1">1</div> 
 
    <div class="div-2">2</div> 
 
    <div class="div-3">3</div> 
 
    <div class="div-4">4</div> 
 
</div>

1

你是靜態分配的div到你的參數的函數裏面,你的變量是私人,因爲他們是在函數內部,這就是爲什麼你不能你的if語句裏面訪問它們。相反,這樣做:

// global variables 
var divOrder, 
    url = document.location.href, 
    divOne = $('.div-1'), 
    divTwo = $('.div-2'), 
    divThree = $('.div-3'), 
    divFour = $('.div-4'); 

divOrder = function (div1, div2, div3, div4) {  
    $('#container').empty().append(div1, div2, div3, div4); 
}; 

// tested it directly 
divOrder(divThree, divTwo, divFour, divOne); 


if (url.indexOf('?test-1') > -1) { 
    divOrder(divFour, divTwo, divThree, divOne); 
} else if (url.indexOf('?test-2') > -1) { 
    divOrder(divThree, divTwo, divFour, divOne); 
} else if (url.indexOf('?test-3') > -1) { 
    divOrder(divOne, divTwo, divFour, divThree); 
} 

JSFiddle