1

重複の可能性:
jQueryを使用してリストをアルファベット順に並べ替えるにはどうすればよいですか?

テクノロジー: jQueryを使用したAsp.net。

こんにちはオタク、

概要:
私はjQuery noobです。このJqueryスクリプトに取り組んでおり、OnEnterキーを押して次の入力要素(textarea、select、inputなど)に移動できるようにしています。独自のソリューションをいくつか試しましたが、利用可能なソリューションも試しました。オンラインですが、すべてのソリューションにはいくつかの弱点や制限があります。私はついに私にとって十分なソリューションを手に入れましたが、それでもいくつかの問題があります。

問題:
属性[tabindex]を持つすべての要素をクエリしましたが、jqueryは階層に存在するDOMのすべての要素を返しますが、要素をtabindexに従って並べ替えたいと思います。

1)したがって、要素は、階層に基づいてではなく、tabindexに基づいて次の要素に移動できるように並べ替える必要があります。
2)いずれかの要素がreadonly="readonly"またはdisabled="disabled"に設定されている場合、その要素はまったくフォーカスを取得しないはずです。

JqueryとHTMLコードを入れて質問を台無しにしたくないので、JsFiddleを作成しました

これに取り組む方法を教えてください。

PS:私にあなたたちがより多くの情報を必要としていることを知らせてください。

4

2 に答える 2

3

ノードの配列を並べ替える方法は簡単です。

まず、NodeListをループして、配列を作成します。各配列要素は[element, thing to sort by]です。この場合、[element, element.tabIndex]

次に、sortコールバックで使用します。

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

これにより、各配列の2番目の要素で並べ替えられます。これは並べ替えの対象です。

必要に応じて、を使用mapして各配列要素を最初の要素に変換します(arr.map(function(a) {return a[0];});

これで、ソートされた要素の配列ができました。

于 2012-05-27T21:24:49.667 に答える
1

注:@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

});​

。選別()

.delegate

デモ

于 2012-05-27T22:08:56.717 に答える