简体   繁体   中英

How to trigger/refer a custom JavaScript object?

I've created a javascript animation object inside a div with #box id, but my problem is I can't refer to the animation object outside the function.

http://codepen.io/vincentccw/pen/bfojB?editors=101

Here is my code:

$('#box').each(function(index, element)
{
          var kkc = new TimelineLite({
            paused:true
          });

          kkc.to($("#box") , .4, {left:100,ease:Power1.easeInOut});

          element.animation = kkc; 

});

$('#box').on('mouseenter', function(){
    $('#box').animation.play(); //this doesn't work
});

In your example, you are mixing up jQuery objects with DOM objects and you use one in one place and the other elsewhere and since they are not the same, your code doesn't work.

When you do:

element.animation = kkc; 

You are adding a custom property named animation to a DOM object.

When you try to do this:

$('#box').animation.play();

You are trying to access a custom property animation on a jQuery object which does not exist.


If you want to stick with the custom DOM property, you could use this code:

$('#box').on('mouseenter', function(){
    this.animation.play(); 
});

because this in your event handler is the DOM object.


The more jQuery way of doing this (which avoids adding your own custom properties to a DOM object) would be like this:

$('.box').each(function(index, element)
{
          var kkc = new TimelineLite({
            paused:true
          });

          kkc.to($(this) , .4, {left:100,ease:Power1.easeInOut});

          $(element).data("animation", kcc); 

});



$('.box').on('mouseenter', function(){
    $(this).data("animation").play();
});

Also, I might ask why you're using $('#box').each() as there should only be one object that matches the #box selector so you shouldn't need to use .each() to iterate.

You can attach the animation to the element using .data() . For example:

var kkc = new TimelineLite({...});
// ...
$('#box').data("animation", kkc);


$('#box').on('mouseenter', function(){
    $('#box').data("animation").play();
});

NB. You used $('#box').each(...) in your sample, which would imply that you expect to have multiple elements with the ID box in the DOM. Normally IDs should be unique within the DOM, so I have removed the unnecessary use of each in the sample code here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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