jQuery-ui/auto-complete/getJSON - 如何将元素的 id 传递给外部 PHP

标签 jquery jquery-ui jquery-ui-autocomplete getjson

我将 jQuery-ui 自动完成绑定(bind)到页面中的多个元素,因为我希望在不同字段中使用同一组选项进行自动完成。像这样的东西:

<input class='myclass' id='myid1' name='field1' type='text' />
<input class='myclass' id='myid2' name='field2' type='text' />
<input class='myclass' id='myid3' name='field3' type='text' />

我正在使用 jquery-ui 自动完成中的“多个远程”选项,因此 JavaScript 看起来像这样:

$(".myclass")
    // don't navigate away from the field on tab when selecting an item
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function(event) {
            if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).data("autocomplete").menu.active) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON("search.php"
                         ,{ term:extractLast(request.term) }
                         ,response);
            },
            search: function() {
                // custom minLength
                var term = extractLast(this.value);
                if (term.length < 1) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
        });

这一切都非常好用。 但我想将 id 作为第二个参数传递给 getJSON。我怎样才能做到这一点?

我知道如何向 $.getJSON 语句添加第二个参数,但我无法获取事件触发器的“id”。我尝试了 $(this).attr('id') 但它给了我未定义。有什么建议吗?

谢谢。

最佳答案

请注意,“source”回调中的 this 是插件的实例,而不是 INPUT 元素。

对 INPUT 的引用实际上保存在插件实例的“element”属性中。
这样做:

source: function( request, response ) {
     var inputID = this.element.attr('id');
     $.getJSON("search.php"
        ,{ term:extractLast(request.term), id: inputID }
        ,response);
},

关于jQuery-ui/auto-complete/getJSON - 如何将元素的 id 传递给外部 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9200188/

相关文章:

javascript - jQuery UI 自动完成传递输入数据

jquery 更改 url 位置

jquery - jquery 获取复选框的当前状态

jQuery UI 对话框定位 - 如何使其保持居中

html - 在 jQuery UI 自动完成中使用 HTML

php - Jquery 用户界面 : autocomplete search by multi data column from mysql db

asp.net-mvc - 具有相同类的多个元素使 jquery click 事件多次触发

javascript - 宽度为 100% 的简单 slider

jquery - 为什么这个简单的 jQuery 切换不起作用?

php - 排序后从列表中获取可排序的 Jquery-ui 数据