How to concatenate variable and string in JavaScript?

前端 未结 1 369
孤街浪徒
孤街浪徒 2020-12-21 22:35

Please don\'t immediately mark this as a duplicate. I\'ve looked at similar questions but still can\'t figure this out.

This is what I have currently:



        
相关标签:
1条回答
  • 2020-12-21 23:13

    The basic problem you have is that there is only ever one value for i. That variable only exists once. The code inside the event handler points to the variable, not to its value when the event handler was created. So take your code that looks like this:

    $("#ldheMenuBarLayer"+i).stop()...
    

    Every time the event handler is run, i will be 2, because we've already gone all the way through the loop.

    You need to use the value of i, not a reference to the variable. You do this by introducing a new scope with an anonymous, immediately-invoked function:

    for(var i=1;i<=2;i++)
    {
        (function(j) {
            $("#MenuBarButton"+j).mouseover(function(){
                $("#ldheMenuBarLayer"+j).stop().animate({height:'66px'},{queue:false, duration:600, easing: 'easeOutBounce'})
            });
            $("#MenuBarButton"+j).mouseout(function(){
                $("#ldheMenuBarLayer"+j).stop().animate({height:'41px'},{queue:false, duration:600, easing: 'easeOutBounce'})
            });
        }(i))
    }
    

    Leaving aside all of this, it's worth mentioning that this isn't a very jQuery-ish way of going about things. The jQuery way might look like this:

    var menuBarButtons = $('.menuBarButton').mouseover(function() {
        var idx = menuBarButtons.index(this);
    
        $('.ldheMenuBarLayer')
            .eq(idx)
            .stop()
            .animate(
                 {
                     height: '66px'
                 },
                 {
                     queue: false,
                     duration: 600,
                     easing: 'easeOutBounce'
                 }
             );
    });
    

    This code won't work (probably). It needs to be based on your markup and page structure. It might ultimately not be possible.

    0 讨论(0)
提交回复
热议问题