简体   繁体   English

为什么此事件仅绑定到与选择器匹配的一个元素?

[英]Why is this event only binding to one element matching the selector?

I have this little piece of jQuery, which is supposed to bind a one-time event to each element matching the selector when they come into view: 我有这小部分的jQuery,应该将一次性事件绑定到与选择器匹配的每个元素,当它们出现时:

jQuery(document).ready(function($) {   
    if (jQuery.browser.mobile === false) {
         $('.featureswrap img.left').css('opacity', 0).one('inview', function(isInView) {
            if (isInView) {$(this).addClass('animated fadeInLeftBig delayp1');}
        });
        $('.featureswrap img.right').css('opacity', 0).one('inview', function(isInView) {
            if (isInView) {$(this).addClass('animated fadeInRightBig delayp1');}
        });
    }
});

However, it only seems to be binding to one (seemingly random) element on the page (per selector, so two total elements). 但是,它似乎仅绑定到页面上的一个(看似随机的)元素(每个选择器,因此共有两个元素)。 At first I thought I was misunderstanding ".one()", but I don't think that's the case. 起初,我以为我误会了“ .one()”,但我认为并非如此。 The CSS function work properly for every element matching the selector, but the inView event only binds to one per selector. CSS函数对于与选择器匹配的每个元素都可以正常工作,但是inView事件仅对每个选择器绑定一个。 Perhaps it is "this" I am misunderstanding, or something else entirely? 也许是我误会的“这个”,或者完全是别的什么?

Some help here would be greatly appreciated. 这里的一些帮助将不胜感激。 The page throws no errors and otherwise works as intended. 该页面不会引发任何错误,否则可以正常工作。 There is no other JavaScript of any kind that could interfere with the event binding or that even interacts with the same elements. 没有任何其他JavaScript可以干扰事件绑定甚至与相同元素进行交互。

Solved this problem by using .each to attach event to each element. 通过使用.each将事件附加到每个元素来解决此问题。 Here's the updated, working code: 这是更新的工作代码:

jQuery(document).ready(function($) {
    if (jQuery.browser.mobile === false) {
        $('.featureswrap img.left').each(function(index){
            $(this).css('opacity', 0).one('inview', function(isInView) {
                if (isInView) {$(this).addClass('animated fadeInLeftBig delayp1');}
            });
        });
        $('.featureswrap img.right').each(function(index){
            $(this).css('opacity', 0).one('inview', function(isInView) {
                if (isInView) {$(this).addClass('animated fadeInRightBig delayp1');}
            });
        });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM