【问题标题】:Sorting Jquery returned HTML elements [duplicate]排序Jquery返回的HTML元素[重复]
【发布时间】:2012-06-02 09:22:29
【问题描述】:

可能重复:
How may I sort a list alphabetically using jQuery?

技术: 带有 jQ​​uery 的 Asp.net。

各位极客,

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

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

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

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

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

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

【问题讨论】:

标签: javascript jquery asp.net html focus


【解决方案1】:

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

首先,遍历 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];});)

您现在有了排序好的元素数组。

【讨论】:

  • 感谢您的输入,但菜鸟需要更多解释:)
【解决方案2】:

注意:无耻地窃取了@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()

.delegate

DEMO

【讨论】:

  • @Jhon 你必须投票给 Kolink,他应得的 :),我只是在验证你的小提琴
  • ':input[tabindex]' 我只想选择具有 tabindex 属性的元素
  • @Jhon .delegate 是 .live 的更新,谢谢
猜你喜欢
  • 2023-03-20
  • 2011-03-04
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 2016-01-18
  • 2020-07-31
  • 2013-07-11
  • 2014-09-04
相关资源
最近更新 更多