在jQuery自动完成源中将元素的id作为url参数发送

jre*_*121 1 jquery user-interface autocomplete

我正在尝试这样做:

$("[type=text]").autocomplete({
    source: "./json.php?id="+$(this).attr("id"),
    minLength: 2
}).addClass("ui-widget ui-widget-content ui-corner-left");
Run Code Online (Sandbox Code Playgroud)

显然这source: "./json.php?id="+$(this).attr("id")不起作用.有谁知道我怎么做到这一点?会有很多自动填充字段,所以我不能使用像这样的选择器$('#ID').

mat*_*t b 6

如果需要同时为多个元素设置此项,请使用each()循环:

$("[type=text]").each(function() {
    var thisEl = $(this);
    thisEl.autocomplete({
        source: "./json.php?id=" + thisEl.attr("id"),
        minLength: 2
    });
    // whatever else you want to do with the element
});
Run Code Online (Sandbox Code Playgroud)


Dar*_*JDG 5

您必须使用在适当的范围内.each()执行来迭代它们.attr():

$("input[type=text]").each(function(){
    $(this).autocomplete({
        source: "./json.php?id="+$(this).attr("id"),
        minLength: 2
    }).addClass("ui-widget ui-widget-content ui-corner-left");
}
Run Code Online (Sandbox Code Playgroud)

编辑:正如评论中所提到的,你有很多字段,比如1500+.您可以尝试通过向每个字段添加一个类,并使用.classname选择器来提高性能,或者至少缩小初始搜索范围input[type="text"],尽管jQuery可能已经为优化做了这些.

您也可以尝试在自动完成的事件createsearch事件中设置源选项,尽管后者可能不起作用.看它的表现并不痛苦:

$("input[type=text]").autocomplete({
    search: function(){
        $(this).autocomplete("option", "source", "./json.php?id="+$(this).attr("id"));
    },
    minLength: 2
}).addClass("ui-widget ui-widget-content ui-corner-left");
Run Code Online (Sandbox Code Playgroud)

或者,您甚至可以绑定到输入字段本身的焦点事件来设置源:

$("input[type=text]").autocomplete({
    minLength: 2
}).focus(function(){
    $(this).autocomplete("option", "source", "./json.php?id="+$(this).attr("id"));
}).addClass("ui-widget ui-widget-content ui-corner-left");
Run Code Online (Sandbox Code Playgroud)

看看是否有任何提高性能,这是一个有趣的测试案例,你已经到达那里.