【问题标题】:.bind to dom objects within .each loop.bind 到 .each 循环中的 dom 对象
【发布时间】:2012-05-31 20:11:28
【问题描述】:

我正在使用 each 遍历 DOM 元素,但是当元素在 .each 循环中可用时,它们将不接受 jQuery 绑定事件。

$('#products .page_item').mouseover(function(){
   console.log('this works, adding the mouseover to every selected element');
});

$('#products .page_item').each(function(index, element){
    element.mouseover(function(){
        console.log("this throws 'not a function'");
    });
});

如何使每个元素在 .each 循环中可用,以便将事件绑定到它们?

谢谢大家。

(我以这种方式迭代元素,因此我可以有条件地从绑定中排除一些元素,FWIW。)

【问题讨论】:

    标签: dom javascript-events jquery


    【解决方案1】:

    您需要将element 包裹在 jQuery 对象中:

    $(element).mouseover(function(){
    

    element(或this)是 DOM 元素,而不是 jQuery 对象。

    完整代码已修复:

    $('#products .page_item').each(function(index, element){
        $(element).mouseover(function(){
            console.log("This works!");
        });
    });
    

    来自each docs

    .each() 方法旨在使 DOM 循环结构简洁且不易出错。 当调用它时,它会遍历作为 jQuery 对象一部分的 DOM 元素。 每次回调运行时,它都会传递当前循环迭代,从 0 开始。更重要的是,回调是在当前 DOM 元素的上下文中触发,因此关键字 this 指的是该元素。

    【讨论】:

      【解决方案2】:

      试试这个代码:

      $('#products .page_item').mouseover(function(){
         console.log('this works, adding the mouseover to every selected element');
      });
      
      $('#products .page_item').each(function(index, element){
          $(element).mouseover(function(){
              console.log("this throws 'not a function'");
          });
      });
      

      【讨论】:

        猜你喜欢
        • 2021-11-23
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 1970-01-01
        • 2013-05-20
        • 2015-11-12
        • 1970-01-01
        • 2012-01-03
        相关资源
        最近更新 更多