如何将hammer.js绑定到多个ID
问题描述:
在页面上,我有几个引导程序传送带,我希望它们可以在刷卡上工作。为此,我使用hammer.js
。将hammer.js
绑定到一个元素并不是问题,例如:如何将hammer.js绑定到多个ID
var swipeElement = document.getElementById('carousel');
if (typeof(swipeElement) != 'undefined' && swipeElement != null) {
var hammertime = new Hammer(swipeElement, {
recognizers: [
[Hammer.Swipe, {direction: Hammer.DIRECTION_HORIZONTAL}]
],
cssProps: {
userSelect: "", contentZooming: ""
}
});
hammertime.on('swiperight', function() {
$('.left.carousel-control').click();
});
hammertime.on('swipeleft', function() {
$('.right.carousel-control').click();
});
}
这是行得通的。但我有几个传送带机智ID:carousel_1
,carousel_2
等。我怎样才能初始化hammer.js
,而无需分别为每个ID编写代码?谢谢。
编辑:
我试图做到这一点:
var swipeElements = document.getElementsByClassName('carousel-inner');
for(var i = 0; i < swipeElements.length; i++) {
if (typeof(swipeElements[i]) != 'undefined' && swipeElements[i] != null) {
var elementId = document.getElementById(swipeElements[i].id);
var hammertime = new Hammer(elementId, {
recognizers: [
[Hammer.Swipe, {direction: Hammer.DIRECTION_HORIZONTAL}]
],
cssProps: {
userSelect: "", contentZooming: ""
}
});
hammertime.on('swiperight', function() {
$(elementId).parent().children('.left.carousel-control').click();
});
hammertime.on('swipeleft', function() {
$(elementId).parent().children('.right.carousel-control').click();
});
}
}
但还是于事无补。如果我代替:
hammertime.on('swipeleft', function() {
$(elementId).parent().children('.right.carousel-control').click();
});
为:
hammertime.on('swipeleft', function() {
$('.right.carousel-control').click();
});
它会触发我的页面上的所有转盘。如果我向右滑动,其他所有传送带也向右滑动。我很困惑...
编辑:由于某种原因$(elementId)
具有价值carousel_6
,但它被放入循环,所以它必须有从carousel_0
值carousel_6
答
只需使用不同的类为每个包装,然后用jQuery来遍历它。
$('.carousel').each(function(i, el){
// el is the actual DOM element
// we save a jQuery wrapped version here in the closure so that
// it is available to callbacks.
var $el = $(el);
var hammertime = new Hammer(el, {
recognizers: [
[Hammer.Swipe, {direction: Hammer.DIRECTION_HORIZONTAL}]
],
cssProps: {
userSelect: "", contentZooming: ""
}
});
hammertime.on('swiperight', function() {
$el.find('.left.carousel-control').click();
});
hammertime.on('swipeleft', function() {
$el.find('.right.carousel-control').click();
});
});
document.querySelectorAll('[选择器匹配所有元素]'),然后'forEach'在那个数组上? –
这样做:'var a = document.querySelectorAll('div.carousel-inner.thumb-inner')'然后'Array.isArray(a)'给我'false'。那么,我该如何使用'forEach'? –
它返回一个NodeList,它也有'forEach'方法 –