如何查找给定元素所在的 jquery 折叠面板的索引

How to find the index for jquery accordion panel that given element is in

本文关键字:jquery 折叠 索引 元素 何查找 查找      更新时间:2023-09-26

我正在使用jQuery手风琴进行多部分注册表单,在提交表单之前,我需要确保填写所有必填字段。 因此,如果我找到未填写的必填字段,我需要打开它所在的手风琴面板,以便我可以将焦点放在用户的该字段上。

我已经有了有问题的元素的 id,所以我可以像这样获得字段的句柄

$('#' + columnname)

但是我不知道如何确定此字段位于哪个面板中。我试过这个:

var accordionindex = $('#' + columnname).closest('.ui-accordion-content').index();

但这似乎不起作用,因为它为第一个面板返回 1,为第二个面板返回 3。如果我减去 1,我最终得到第一个面板的 0(这是正确的),第二个面板的 2(仍然不正确)。

我也试过:

var accordionindex = $('#' + columnname).closest("H4").index()

但这为所有面板返回 -1。

我的手风琴是这样启动的:

$('#registration').accordion({
     collapsible: false,
     header: 'h4',
     heightStyle: 'content',
     active: 0
})

当然,有一种简单的方法可以做到这一点。

也可以从手风琴的数据中提取面板索引:

// id is like 'ui-accordion-accordion-panel-2'
var elems = $('#' + columnname).closest('.ui-accordion-content').attr('id').split('-');
var accordionindex = parseInt(elems[elems.length - 1], 10);

Plunker 演示(检查脚本中的代码.js)。

Working Fiddle

您可以使用数据属性来存储手风琴中每个面板的索引,然后在尝试激活输入面板时获取它,请查看下面的示例。

.HTML:

<div id="accordion">
  <h3><a href="#">Section 1</a></h3>
  <div data-index='0'>
    <p>Section 1 Content</p>
  </div>
  <h3><a href="#">Section 2</a></h3>
  <div data-index='1'>
    <p>Section 2 Content</p>
  </div>
  <h3><a href="#">Section 3</a></h3>
  <div data-index='2'>
    <p>
       Section 3 Content
      <input id="test" type='text'>
    </p>
  </div>
  <h3><a href="#">Section 4</a></h3>
  <div data-index='3'>
    <p>Section 4 Content</p>
  </div>
</div>

.JS:

$(function() {
      $("#accordion").accordion({ autoHeight: true, collapsible: true});
      //Get panel index of input `#test` 
      var index = $('#test').closest('.ui-accordion-content').data('index');
      //Active panel of input `#test` 
      $( "#accordion" ).accordion( "option", "active", index );
});

希望这有帮助。