【问题标题】:Update variable inside object inside loop更新循环内对象内的变量
【发布时间】:2015-12-11 13:36:01
【问题描述】:

将尝试解释该问题,如果没有意义,请见谅: 我正在尝试在循环时更新对象内的变量。 试图定位类元素的所有父级以在 scrollmagic 插件上使用。 这是我的代码的样子:

var childElement = $('.child');
var myparents = [];

    var getParent = function () {
        childElement.each(function() {
            var theParent = $(this).closest('.parent');
            myparents.push(theParent);
        });         
    }();    

    for (var i=0; i<childElement.length; i++) {
        // also using the loop to add animation to every element, 
        // that's why the loop through other elements
        new ScrollMagic.Scene({
            // here is where I would need to access each
            triggerElement: myparents[i],
            triggerHook: 'onEnter'
        })
    }

元素已成功添加到数组中,并且可以使用它们,但无法在此滚动魔术(对象?)中访问它们。 非常感谢任何提供帮助的人。

【问题讨论】:

  • 仅仅因为您调用了一个方法 (ScrollMagic.Scene) 并传入了一个对象 {triggerElement: thing, triggerHook: thing2} 并不意味着这些值一定可以用作您的对象的属性。这将取决于 scrollmagic API。

标签: javascript jquery arrays loops object


【解决方案1】:

您可以轻松使用更短的代码版本,该版本不易出错,并且更易于“作为独立模块”使用,因为它不会污染范围。

$('.child').each(function(){
    var $child = $(this),
        $parent = $child.closest('.parent');
    $child.data('scrollMagic',new ScrollMagic.Scene({
        triggerElement: $parent[0],
        triggerHook: 'onEnter'
    });
});

当您知道孩子时,如果您现在需要访问 scrollMagic 对象,您只需访问 $(&lt;childElement&gt;).data('scrollMagic')

但是,如果对象本身在onEnter 挂钩中可用,则取决于scrollMagic 插件的实现方式。这与这段代码无关。

【讨论】:

  • 很高兴为您提供帮助!如果你继续沿着 jQuery/webdev/javascript 的路径走下去:记住这个例子,你可以轻松地创建自包含代码:-)
【解决方案2】:

你为什么不这样使用:

var childElement = $('.child');
 childElement.each(function() {
    var theParent = $(this).closest('.parent');
    new ScrollMagic.Scene({
       triggerElement: theParent,
       triggerHook: 'onEnter'
    });
 });

【讨论】:

  • 这实际上是我的第一种方法,但不幸的是没有奏效
  • 你能尝试在 each(function(passedParamter) ..) 中传递一个参数并使用 $(passedParameter).closest 而不是 $(this) 吗?
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 2018-12-25
  • 2011-02-19
  • 1970-01-01
相关资源
最近更新 更多