如何防止jQueryUI Autocomplete的默认键盘交互?

时间:2012-10-27 01:53:15

标签: javascript jquery jquery-ui jquery-ui-autocomplete keyboard-events

当我按下ENTER以防止jQueryUI Autocomplete选择当前关注的项目并关闭菜单时,我特别想阻止交互。

我指的是以下文档:http://api.jqueryui.com/autocomplete/#event-change enter image description here

1 个答案:

答案 0 :(得分:1)

<强>更新

原则是一样的。只需更改setTimeout功能即可提交您的表单(如此处所示:http://jsfiddle.net/X8Ghc/8/

<强>更新

你是对的,$(this)应该引用ui-menu(显然没有)。新的小提琴http://jsfiddle.net/X8Ghc/7/,运作得相当好。

$(document).ready(function() {
    $("#autocomplete").autocomplete({
        "open": function(e, ui) {
            //using the 'open' event to capture the originally typed text
            var self = $(this),
                val = self.val();
            //saving original search term in 'data'.
            self.data('searchTerm', val);
        },
        "select": function(e, ui) {
            var self = $(this),
                keyPressed = e.keyCode,
                keyWasEnter = e.keyCode === 13,
                useSelection = true,
                val = self.data('searchTerm');
            if (keyPressed) {
                if (keyWasEnter) {
                    useSelection = false;
                    e.preventDefault();
                    window.setTimeout(function() {
                        //since there is apparently no way to prevent this
                        //contemptible menu from closing, re-open the menu
                        //using the original search term after this handler
                        //finishes executing (using 'setTimeout' with a delay
                        //of 0 milliseconds).
                        self.val(val);
                        self.autocomplete('search', val);
                    }, 0);
                }
            }
            return useSelection;
        },
        "source": ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
    });
});​

<强>原始

这适用于a fiddle

$(document).ready(function() {
    $("#autocomplete").autocomplete({
        "select": function(e, ui) {
            var keyPressed = e.keyCode,
                keyWasEnter = e.keyCode === 13,
                useSelection = true;
            console.log(e);
            if (keyPressed) {
                if (keyWasEnter) {
                    useSelection = false;
                    $(this).open(e, ui);
                }
            }
            return useSelection;
        },
        "source": ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
    });
});​