单击此子项中的链接添加关闭功能

时间:2017-06-13 02:10:21

标签: javascript jquery html

我有这个响应式jquery菜单,支持:

 (function($) {
  $.fn.collapsable = function(options) {
    // iterate and reformat each matched element
    return this.each(function() {
      // cache this:
      var obj = $(this);
      var tree = obj.next('.navigation');
      obj.click(function(){
        if( obj.is(':visible') ){tree.toggle();}
      });
      $(window).resize(function(){
        if ( $(window).width() <= 780 ){tree.attr('style','');};
      });
    });
  };

  $(document).ready(function(){
    $('.slide-trigger').collapsable();
  });  
})(jQuery);

并使用此HTML结构

<nav id="navigation">
 <div class="navheader slide-trigger">&#9776;<span></span></div>
  <ul class="navigation group">
    <li><a href="#slide1">Link 1</a></li>
    <li><a href="#slide2">Link 2</a></li>
    <li><a href="#slide3">Link 3</a></li>
    <li class="ctoa"><a href="#c2a">Link 4</a></li>
  </ul>
 </nav>

我不能为我的生活弄清楚如何设置当单击列表块中的A时,它会导致菜单崩溃。因为这是一个单页网站,所以不能让它保持打开状态。

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

      $('ul.navigation li a').click(
      function(e)
      {
        e.preventDefault();
        $('.slide-trigger').click();
      });

希望这会有所帮助:)

答案 1 :(得分:1)

您是否尝试为树对象本身添加切换功能? 这段代码未经测试,但也许是这样的..

    (function($) {
  $.fn.collapsable = function(options) {
    // iterate and reformat each matched element
    return this.each(function() {
      // cache this:
      var obj = $(this);
      var tree = obj.next('.navigation');
      obj.click(function(){
        if( obj.is(':visible') ){tree.toggle();}
      });

      // added tree toggle
      tree.click(function(){
          if( tree.is(':visible') ){tree.toggle();}
      });

      $(window).resize(function(){
        if ( $(window).width() <= 780 ){tree.attr('style','');};
      });
    });
  };

  $(document).ready(function(){
    $('.slide-trigger').collapsable();
  });  
})(jQuery);

答案 2 :(得分:1)

您可以使用.add

obj.add(tree.find('a')).click(function(){

演示

&#13;
&#13;
$(document).ready(function(){
  $('.slide-trigger').collapsable();
}); 

//(function($) {
  $.fn.collapsable = function(options) {
    // iterate and reformat each matched element
    //return this.each(function() {
      // cache this:
      var obj = $(this);
      var tree = obj.next('.navigation');
      tree.hide();
      obj.add(tree.find('a')).click(function(){
        if( obj.is(':visible') ){tree.toggle();}
      });
      $(window).resize(function(){
        if ( $(window).width() <= 780 ){tree.attr('style','');};
      });
    //});
  }; 
//})(jQuery);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav id="navigation">
 <div class="navheader slide-trigger">&#9776;<span></span></div>
  <ul class="navigation group">
    <li><a href="#slide1">Link 1</a></li>
    <li><a href="#slide2">Link 2</a></li>
    <li><a href="#slide3">Link 3</a></li>
    <li class="ctoa"><a href="#c2a">Link 4</a></li>
  </ul>
 </nav>
&#13;
&#13;
&#13;

你可以看看