Can't get $(this) working in jQueryUI autocomplete

后端 未结 5 1481
滥情空心
滥情空心 2020-12-25 11:21

I\'m trying to create a generic autocomplete script using jQueryUI. The autocomplete should work for every:



        
5条回答
  •  -上瘾入骨i
    2020-12-25 11:59

    Setup autocomplete separately for each item in your selection, using a closure to hold a reference to the relevant element. Something like the following:

    $('input.autocomplete').each(function(i, el) {
        el = $(el);
        el.autocomplete({
            source: function(req, add) {
                var id = el.attr('id');
                alert(id);
            }
        });
    });
    

    Alternative (edit)

    I don't see why there is such resistance to using each(): it works, the code is very clear and readable, and it introduces no issues with efficiency; but if you're determined to avoid each(), here's an alternative...

    *PLEASE NOTE: the following approach relies (a little bit) on the internals of jQuery Autocomplete, so I'd recommend the first option... but the choice is yours.

    $('input.autocomplete').autocomplete({
            source: function(req, add) {
                var id = this.element.attr('id');
                alert(id);
            }
        });
    });
    

    That will work, at least until/unless they change the way the source() function is called from within the autocomplete plugin.

    So, you have two options... something for everyone.

提交回复
热议问题