0

我为我的网站使用了自动完成插件。这对我来说效果很好。但是现在因为我同时使用了 Ajax 所以在使用 AJax 添加新的 HTML 时,我的脚本失败了。我在stackoverflow上发布并得到了关于使用.onJquery 1.7.2的答案所以我试图将我的代码绑定到.on

我的代码是

$(document).ready(function(){
    $(function(){
        $(document).on("click.autocomplete","#artist_id",function(e){
            $(this).autocomplete({
                source : '<?php echo HTTP_PATH . '/artists/getArtistList'; ?>',
                multiple: true,
                mustMatch: true,
                matchContains: true,
                scroll: true,
                minChars: 0,
                autoFill: true,
                dataType: "json",
                parse: function(data) {
                    return $.map(data, function(item) {
                        return { data: item, value: item.label, result: item.label};
                    });
                },
                formatItem: function(item) {
                    return item.label;
                },
                formatResult: function(item) {
                    return item.id;
                },
                formatMatch: function(item) {
                    return item.label;
                }
            });
        });
    });
 });

运行良好的代码...

    $("#artist_id").focus().autocomplete( '<?php //echo HTTP_PATH . '/artists/getArtistList'; ?>', {
        multiple: true,
        mustMatch: true,
        matchContains: true,
        scroll: true,
        minChars: 0,
        autoFill: true,
        dataType: "json",
        parse: function(data) {
            return $.map(data, function(item) {
                return { data: item, value: item.label, result: item.label};
            });
        },
        formatItem: function(item) {
            return item.label;
        },
        formatResult: function(item) {
            return item.id;
        },
        formatMatch: function(item) {
            return item.label;
        }
    });

问题既不是它发送响应也不是给我脚本错误。我尝试使用 Firebug 检查它。

4

2 回答 2

0

Few things:

This is redundant

$(document).ready(function(){
    $(function(){...

only use one or the other.

$(document).ready(function(){...

Secondly, click.autocomplete binds to any click events that have the autocomplete namespace. What i think you meant to do is to bind the event to any text input that has the class autocomplete.

$(document).on("click",".autocomplete",function(e){
    // prevent the default action
    e.preventDefault();
    // initialize autocomplete
    $(this).autocomplete({
        ...
    })
    // remove class to prevent reinitializing autocomplete:
    .removeClass('autocomplete')
    // trigger the focus event to start the autocomplete
    .focus();
});

$(document).ready isn't needed here since the document is already ready.

于 2012-06-29T19:02:39.760 回答
0

你的问题是这一行:

$(document).on("click.autocomplete","#artist_id",function(e){

您以前在焦点上“绑定”,现在您在“click.autocomplete”上绑定。将其更改为:

$(document).on("focus","#artist_id",function(e){

根据.on() 上的 jQuery 文档,第二个参数是您要绑定的事件,而不是选择器。

于 2012-06-29T18:21:01.940 回答