我认为(希望)这是一个简单的问题。我不完全理解我在这里所做的事情,所以任何帮助都会很棒!
我在容器内有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 :(得分: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 :(得分: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);
}