【问题标题】:jQuery-ui / auto-complete / getJSON - How to pass the id of the element to the external PHPjQuery-ui / auto-complete / getJSON - 如何将元素的 id 传递给外部 PHP
【发布时间】:2022-01-31 18:54:27
【问题描述】:

我将 jQuery-ui 自动完成绑定到页面中的多个元素,因为我希望在不同字段中使用相同的选项集进行自动完成。比如:

<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') 但它给了我 undefined。有什么建议吗?

谢谢。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多