jQuery-为什么我不能在循环中将事件绑定到元素? [英] jQuery - why can't I bind events to elements in a loop?

查看:98
本文介绍了jQuery-为什么我不能在循环中将事件绑定到元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

  var b = $(slipStream.conf.mainVis).find('p#prev');
  b.click(function() {
    slipStream.slideLeft();
        return false;
  });

  b = $(slipStream.conf.mainVis).find('p#next');
  b.click(function() {
    slipStream.slideRight();
        return false;
  });

  b = $(slipStream.conf.controls).find('li img');
  console.log(b);
  for (var l in b) {
        l.click(function() {
              var visIndex = l.index();
              console.log(visIndex);
        });
  };

通过前两个绑定,没问题.但是我无法遍历集合并将某些东西绑定到每个成员吗? (控制台告诉我"l.click不是函数.")这是jQuery的限制还是我的代码无效?不过,这似乎是解决问题的方法.

The first two bindings go through, no problem. But I can't loop through a collection and bind something to each member? (the console is telling me that "l.click is not a function.") Is this a limitation of jQuery or is my code off? This seems like it would be the way to do it, though...

推荐答案

枚举jQuery对象时,枚举的值是实际的DOM节点,而不是jQuery包装器.因此,它们没有click方法,但是您可以再次包装它们以获得所有通常的功能.

When you enumerate over a jQuery object, the values being enumerated are actual DOM nodes and not jQuery wrappers. Therefore, they don't have a click method but you can wrap them again to get all the usual functionality.

当然这不是必需的,因为您可以直接从初始jQuery实例直接附加包装器:

Of course this is not necessary because you can simply attach a wrapper directly from your initial jQuery instance:

$(slipStream.conf.controls).find('li img').click(function() {
    var visIndex = $(this).index();
    console.log(visIndex);
});

这篇关于jQuery-为什么我不能在循环中将事件绑定到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆