Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何按节点深度排序,然后按tabindex排序?_Javascript_Jquery - Fatal编程技术网

Javascript 如何按节点深度排序,然后按tabindex排序?

Javascript 如何按节点深度排序,然后按tabindex排序?,javascript,jquery,Javascript,Jquery,我有一个HTML表单,它是在运行时使用模板动态构建的,由用户操作决定 我需要根据表单的每个部分中指定的tabindexing设置整个表单的tab索引 鉴于此,jQuery中是否有一种方法可以对集合中的项目进行排序?例如,遵循这个伪结构的东西会很棒,但我不知道如何实现它: <div name="firstTemplate" templateIndex="0"> <input type="text" name="field0" tabIndex="1" />

我有一个HTML表单,它是在运行时使用模板动态构建的,由用户操作决定

我需要根据表单的每个部分中指定的tabindexing设置整个表单的tab索引

鉴于此,jQuery中是否有一种方法可以对集合中的项目进行排序?例如,遵循这个伪结构的东西会很棒,但我不知道如何实现它:

<div name="firstTemplate" templateIndex="0">
    <input type="text" name="field0" tabIndex="1" />
    <input type="text" name="field1" tabIndex="2" />
    <input type="text" name="field2" tabIndex="3" />
</div>
<div name="firstTemplateRpt" templateIndex="1">
    <input type="text" name="field0" tabIndex="1" />
    <input type="text" name="field1" tabIndex="2" />
    <input type="text" name="field2" tabIndex="3" />
</div>
<div name="secondTemplate" templateIndex="2">
    <input type="text" name="field0" tabIndex="1" />
    <input type="text" name="field1" tabIndex="2" />
    <input type="text" name="field2" tabIndex="3" />
</div>
其中templateIndex是表单中模板的索引,tabindex是模板中控件的tabindex。模板可以在运行时多次添加到表单中,这会对手动指定的tabindex造成严重破坏

将另一个模板添加到表单中时,将为其分配templateIndex=“3”,手动设置的tabIndexes从1开始。将具有templateIndex属性的div收集到数组中,然后按如下方式排序:

divArray.sort(function(a, b) {
    return a.getAttribute('templateIndex') - b.getAttribute('templateIndex');
});
然后使用非常类似的函数对这些输入进行迭代,并对数组中的输入进行排序:

inpArray.sort(function(a, b) {
    return a.tabIndex - b.tabIndex;
});

然后使用node.parentNode.insertBefore(node,firstChild)之类的方法在文档中按所需顺序移动元素。

我想你已经找到了关键,我会试试看。我不想移动文档中的字段,我只想调整tabindexes,使它们按从1到n的顺序运行,其中n是字段数。我想你给我的东西会帮助我实现这个目标,谢谢。好的,那么你只需要在节点上迭代,并根据循环计数器添加属性。您可以使用集合来实现这一点,也可以使用递归遍历DOM来实现无限(或定义但可变)深度。随便什么都行。
inpArray.sort(function(a, b) {
    return a.tabIndex - b.tabIndex;
});