Trigger jquery accordion menu by an event?

给你一囗甜甜゛ 提交于 2020-01-12 14:12:54

问题


Is it possible to open the next panel in a jquery accordion menu through a seperate button onclick event? That is instead of clicking the heading to open another panel, use a button not connected to the accordion.


回答1:


Yes, just call activate on the accordion like this:

$("#myaccordion").accordion("activate", 1 );

Where 1 is the index you want to open.

You can get the current zero-based index of the active panel by calling:

var index = $("#myaccordion").accordion('option','active');

So, taking both these items together, we can open the next item on a click:

$("#mybutton").click(function(e){
  e.preventDefault();
  var acc   = $("#myaccordion"),
      index = acc.accordion('option','active'),
      total = acc.children('div').length,
      nxt   = index + 1;

  if (nxt >= total) {
     nxt = 0; // Loop around to the first item
  }

  acc.accordion('activate', nxt);
})



回答2:


In versions of JQuery UI 1.10 or greater the .activate function has been deprecated in favour of using the 'option' method so an alternative approach using the previous answer and would be:

$("#button").click(function(){
    var index = $("#accordion").accordion('option','active');
    var total = $("#accordion").children('div').length;
    index++;

    // include restart same as previous answer     
    if (index >= total) {
        index = 0;
    }

    $("#accordion").accordion("option", "active", index);

}


来源:https://stackoverflow.com/questions/3027040/trigger-jquery-accordion-menu-by-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!