排序 Jquery 返回的 HTML 元素

Sorting Jquery returned HTML elements

本文关键字:HTML 元素 返回 Jquery 排序      更新时间:2023-09-26

可能的重复项:
如何使用 jQuery 按字母顺序对列表进行排序?

技术:Asp.net jQuery。

嗨,极客们,

概述:
我是一个jQuery菜鸟,我一直在研究这个Jquery脚本,使OnEnter按键移动到下一个输入元素(文本区域,选择,输入等),我已经尝试了自己的几种解决方案,甚至尝试了在线可用的解决方案,但是每个解决方案都有一些弱点或局限性,好吧,我终于得到了一个对我来说足够好的解决方案,但它仍然存在一些问题。

问题:
我已经查询了所有具有属性 [tabindex] 的元素,现在 jquery 返回 DOM 中的所有元素,因为它们存在于它们的层次结构中,但我希望元素根据它们的 tabindex 进行排序。

1)所以元素需要排序,以便我可以根据tabindex而不是基于它们的层次结构移动到下一个元素。
2)如果任何元素设置为readonly="readonly"或禁用="禁用",该元素根本不应该得到焦点怎么办?

我不想通过放置Jquery和HTML代码来搞砸问题,所以我创建了JsFiddle

让我知道如何解决这个问题。

附言:让我知道你们需要更多信息。

我对任何节点数组进行排序的方式很简单。

首先,遍历 NodeList 并构建一个数组。每个数组元素都是[element, thing to sort by] 。在这种情况下,[element, element.tabIndex] .

然后,将sort与回调一起使用:

arr.sort(function(a,b) {return a[1]-b[1];});

这将按每个数组的第二个元素进行排序,这是要排序的内容。

(可选)使用 map 将每个数组元素转换为其第一个元素 ( arr.map(function(a) {return a[0];});

现在,您已经有了已排序的元素数组。

注意:无耻地窃取了@Kolink的想法

$(document).ready(function () {            
     var arr=$(":input[tabindex]:not('[disabled=disabled],[readonly=readonly]')");//this will give you the input elements that are not disabled or readonly
     //as Kolink mentioned in his answer use the .sort function of javascript array to sort the array according to the tab index 
     var newArr=arr.sort(function(a,b){   
     return a[1]-b[1];
     });
     console.log(newArr);
     $(newArr[0]).select().focus(); // focus the element with tabindex=1
     var $currentFocus=0;//set the currentFocus pointer to the first element of the sorted array
     var $arrLen = newArr.length;
 $(':input').live("keydown", function (e) {        DO NOT USE .live as it is deprecated but i will go with it for the time being see the link to .delegate at the end of the answer                  
  if (e.which == 13) //Enter key
   {
     e.preventDefault();     
     if($currentFocus<$arrLen){     
        $(newArr[$currentFocus+1]).focus();     
        $currentFocus++;     //increment the pointer    
     }else {
        console.log("submit form");
        alert("submit form");
     }
   }
 }); //end of keydown function
});​

.sort()

。委托

演示