質問

I've checked through the forum and cant seem to find a solution to my problem.

I have an array of id's and I'm iterating through them with a for loop adding mouse events for enter and leave. However the events all bind to the final ID, which is probably a for each issue.

I've put it up on a fiddle below, any help would be appreciated - my brain is a bit frazzled today.

http://jsfiddle.net/shanemccster/e48vu/4/

cards = new Array('#box0','#box1','#box2');
function bindCardEvents(){
    for (var i=0; i<cards.length; i++){
        var targetID = '#'+$(cards[i]).attr('id');
        $(targetID)
            .mouseenter(function() {
                TweenMax.to(targetID,0.3, {opacity:0.5} )
            }).mouseleave(function() {
                TweenMax.to(targetID,0.3, {opacity:1}) 
            }); 
    }
}
bindCardEvents();

Thanks

役に立ちましたか?

解決 2

jsFiddle Demo

You can just join the ids together with , which by convention adds the selectors to a set in jQuery. After doing that, you can assign the event to the set returned by those selectors. Each event will have access to the current element this. TweenMax.to expects a selector or an element, so you can pass this into the function without manually constructing an id selector.

var cards = new Array('#box0','#box1','#box2');
var cardSelector = cards.join(",");
function bindCardEvents(){
  $(cardSelector).mouseenter(function() {
    TweenMax.to(this,0.3, {opacity:0.5} )
  }).mouseleave(function() {
    TweenMax.to(this,0.3, {opacity:1}) 
  });
}
bindCardEvents();

For brevity this will also work

$(cards.join(",")).mouseenter(function() {
    TweenMax.to(this,0.3, {opacity:0.5} )
  }).mouseleave(function() {
    TweenMax.to(this,0.3, {opacity:1}) 
});

他のヒント

You dont have to iterate. You can use like

   $("[id^=box]")
        .mouseenter(function() {
            TweenMax.to(this,0.3, {opacity:0.5} )
        }).mouseleave(function() {
            TweenMax.to(this,0.3, {opacity:1}) 
        }); 

It will bind the events to all the elements whose id starts with box

Demo

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top