jQuery functions not working with Hammer.js

跟風遠走 提交于 2019-12-02 08:39:51

问题


I am trying to add press to jQuery selector. I have many elements on same document, So I can not use IDs for each. I tried by $(selector)[i] as like explained here.

var selectProduct = $('.mh60 a');
for (var i = 0; i < selectProduct.length; i++) {
  Hammer(selectProduct[i]).on("press", function() {
     $(selectProduct[i]).addClass('active');
  });
}

It's not producing any error and not working. I didn't get what I am missing here.

And when I try to log selectProduct[i] by console.log(selectProduct[i]); it gives undefined result.

UPDATE 1

When I remove for loop and just use selectProduct[0] , selectProduct[1] , ... it's working but with selectProduct[i] , it's not working, So I think problem is on for loop. But I didn't get it.

UPDATE 2

I also tried with jQuery plugin, same problem

UPDATE 3

Again I tried with each(), same problem. It print the console message but addClass() is not working. I guess the problem is with this function which is not returning the current element.

$('.mh60 a').each(function(){
    var mc = new Hammer(this);
    mc.on("press", function() {
      console.log('Double tap!');
      $(this).addClass('active');
    });
 });

回答1:


Why do you use a for? Try changing your code like this

var selectProduct = $('.mh60 a');
selectProduct.Hammer().on("press", function() {
  $(this).addClass('active');
});



回答2:


Finally I solved the problem by using each function

$('.mh60 a').each(function(){
    var mc = new Hammer(this);
    var currentEle = $(this);
    mc.on("press", function() {
      currentEle.addClass('active');
    });
 });


来源:https://stackoverflow.com/questions/38101901/jquery-functions-not-working-with-hammer-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!