dsf6778 2016-10-18 19:33
浏览 39
已采纳

在Magento菜单上自定义javascript

I'm trying to add a custom java-script file into Magento by placing the following into local.xml

<action method="addJs"><script>nav/navigation.js</script></action>

navigation.js

$sub = $('div.col-md-2.right-content');
$('div.col-md-10').on({
    mouseenter: function() {
        var i = $(this).index();
        $sub.addClass('li-'+i);
    }, mouseleave: function() {
        $sub.removeClass().addClass('col-md-2.right-content');

    }
})

style.css

li.level2.nav-2-1-1.first{
    background-color: green;
    }
li.level2.nav-2-1-2.last{
    background-color: red;
    }

The purpose of this is that whenever a user hover over a link inside my submenu, the right-content will change accordingly. The problem is that my navigation.js file is targeting objects that does not exist until after the menu is loaded. These being 'div.col-md-2.right-content' and 'div.col-md-10'.

Is there a way to load the javascript after the menu has loaded? Or is there another way to accomplish this? Or am I just approaching this completely wrong.

  • 写回答

2条回答 默认 最新

  • drf97973 2016-10-18 19:42
    关注

    You can use the $(function() { ... } ) syntax to have that code run only after all of your DOM is loaded:

    $(function() {
        $sub = $('div.col-md-2.right-content');
        $('div.col-md-10').on({
            mouseenter: function() {
                var i = $(this).index();
                $sub.addClass('li-'+i);
            }, mouseleave: function() {
                $sub.removeClass().addClass('col-md-2.right-content');
            }
        })
    })
    

    Note that this will work only if the menu is part of your original DOM (part of the HTML code) and not created dynamically.

    In case the menu is generated dynamically you can use:

    $('body').on('mouseenter', 'div.col-md-10', function() { ... });
    

    Here is a working example:

    $(function() {
                        
      $sub = $('.subject');
      $('body')
      .on('mouseenter', '.yeah', function() {
        var i = $(this).index();
        $sub.addClass('li-'+i);
      })
      .on('mouseleave', '.yeah', function() {
        $sub.removeClass().addClass('subject');
      })
      
      $('.test').append($('  <ul>    <li class="yeah"><a href="#">Link 1</a></li>     <li class="yeah"><a href="#">Link 1</a></li>     <li class="yeah"><a href="#">Link 1</a></li>   </ul>'));
      
    });
    .li-0{
      background-color:green;
    }
    
    .li-1{
      background-color:red;
    }
    
    .li-2{
      background-color:blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test">
    
    </div>
    
    <div class="subject">
      <p>hello</p>
    </div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?