所以我有这个旋转木马,但似乎没有工作,我不知道为什么。我在$(document).ready()
内有此功能,但是当我点击next
/ prev
时,它不起作用。所以我想也许我做错了什么,因为它似乎根本没有把它拿起来。
HTML:
<div id="jb-video-carousel">
<span class="business-left"></span>
<ul class="jb-videos-container">
<li class="jb-video-container">test</li>
<li class="jb-video-container">test</li>
<li class="jb-video-container">test</li>
<li class="jb-video-container">test</li>
</ul>
<span class="business-right"></span>
</div>
JS:
(function () {
var defaults = {
container: '.jb-videos-container',
wrap: '.jb-video-carousel',
item: '.jb-video-container',
btnPrev: '.business-left',
btnNext: '.business-right'
};
var itemsPerPage = 0,
totalPages = 0,
page = 1,
$items = $(defaults.item, el),
$wrapper = $(defaults.wrap, el),
$container = $(defaults.container, el),
$next = $(defaults.btnNext, el),
$prev = $(defaults.btnPrev, el),
itemWidth = $items.eq(0).outerWidth(true),
margin = itemWidth - $items.eq(0).width(),
moveToPage = function (n) {
var scalar = n > 1 ? n - 1 : 0,
rem = $items.length - (scalar * itemsPerPage),
left = 0;
if (rem < itemsPerPage) {
left = (($items.length) * itemWidth) - $wrapper.width();
} else {
left = scalar * (itemsPerPage * itemWidth);
}
$container.css('left', -left);
page = n;
},
layout = function () {
itemsPerPage = Math.floor(($wrapper.outerWidth() + margin) / itemWidth);
totalPages = Math.ceil($items.length / itemsPerPage);
if (totalPages === 1) {
$prev.hide();
$next.hide();
}
else {
$prev.show();
$next.show();
}
},
onResize = function () {
layout();
moveToPage(page);
},
pagePrev = function () {
var destination = page - 1;
if (destination <= 0) {
destination = 1;
}
moveToPage(destination);
},
pageNext = function () {
var destination = page + 1;
if (destination > totalPages) {
destination = totalPages;
}
moveToPage(destination);
};
$container.css({
'position': 'absolute',
'width': (itemWidth * $items.length)
});
$(window).on('resize', function (evt) {
onResize(evt);
});
$next.on('click', function (evt) {
pageNext();
return false;
});
$prev.on('click', function (evt) {
pagePrev();
return false;
});
domready(function () {
setTimeout(onResize);
});
});
答案 0 :(得分:3)
您的匿名函数根本没有执行:
(function() {}); // declares an anonymous function (useless)
(function() {})(); // declares AND EXECUTES an anonymous function instantly
因此,您必须在最后一个分号之前添加一对括号。
答案 1 :(得分:1)
声明函数和执行函数之间存在差异。你在代码中执行它的原因是声明一个匿名函数。为了调用该函数,您应该在其末尾添加一对括号()
,然后使用分号;
,如:
(function() {
// function definition
}());