簡體   English   中英

jQuery的UI自動完成防止Tab鍵焦點

[英]jquery-ui autocomplete prevent tab key focus

發布回答我自己的問題:

我有以下HTML:

    <select id="genre-select">
        <option value="-1">Make a selection</option>
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
    </select>
    <input id="band-input" type="text" />
    <button id="go-button">Go</button>
    <button>Unrelated Button</button>

我正在使用jquery-ui自動完成對象,我的原始javascript如下所示:

            var bandValue = "-1";
            var $genreSelect = $("#genre-select");
            var $bandInput = $("#band-input");
            var $goButton = $("#go-button");
            var bands = [
              {
                value: "1",
                label: "AC/DC",
                desc: "..."
              },
              {
                value: "2",
                label: "Black Sabbath",
                desc: "Ozzy Osbourne, Tony Iommi, Bill Ward, etc."
              },
              {
                value: "3",
                label: "Cars, The",
                desc: "..."
              }
            ];
            $bandInput.autocomplete({
              source: bands,
              focus: function( event, ui ) {
                $bandInput.val( ui.item.label );
                return false;
              },                  
              select: function( event, ui ) {
                console.log("select event");
                bandValue = ui.item.value;
                $bandInput.val(ui.item.label);          
                return false;
              }           
            }); 

它起作用了,但是當使用鍵盤導航並按TAB時,焦點將跳到“無關按鈕”,而不是預期的“開始”按鈕。 我試圖吞噬所有按鍵和單擊事件,並完全控制$ goButton何時獲得焦點,但沒有任何效果。

經過大量的故障排除后,該解決方案實際上非常簡單。 如果autocomplete.select事件來自TAB,我只需跳過對$ goButton.focus()的調用,並允許常規事件來完成它的工作。

            $bandInput.autocomplete({
              source: bands,
              focus: function( event, ui ) {
                $bandInput.val( ui.item.label );
                return false;
              },                  
              select: function( event, ui ) {
                bandValue = ui.item.value;
                $bandInput.val(ui.item.label);
                if(event.which != null){
                    if(event.which != 9){
                        //it's not a tab, so focus
                        $goButton.focus();
                    }
                    else {
                        //already going to focus, so don't create race condition
                    }
                }               
                return false;
              }           
            }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM