Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

jquery - Add a link to a JQueryUI autocomplete item

When a user starts typing on the searchbox, the suggestion page returns the latest item from all collections matching that nama, plus other data.

I'd like to show that item (along its image), and a link to "see all items from this collection".

I can do (most of) that with the following code:

$('#search').autocomplete({
    source: function (request, response) {
        $.ajax({
            url: suggesturl,
            dataType: 'json',
            data: request,
            success: function (data) {
                response(data.map(function (value) {
                    return {
                        'label': '<img src="' + value.thumbsmall + '" />' + value.name + '<a href="/">More items from this collection...</a>',
                        'value': value.fullname
                    };  
                }));
            }   
        }); 
    },  
    minLength: 3
})

The problem is that, although the link appears in the box, when it's clicked it gets ignored, and the default select action is executed (the item's value is put into the textbox).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Seems like you have a couple options. First, you can specify your own select action, using a select option on the autocomplete initializer.

$(selector).autocomplete({
    source: ... ,
    select: function(value, data){
          if (typeof data == "undefined") {
              emitMessage('You selected: ' + value + "<br/>");
          } else {
              emitMessage('You selected: ' + data.item.value + "<br/>");
          }
    }
});

If that is not sufficient, for some reason, then you can render your own content for the autocomplete list, and in that way get as much control as you need.
You do that by monkey-patching the _renderItem fn, which is what autocomplete calls to render each item in the list. Check this answer for how to do it. It works in v1.8rc3.

I suppose in _renderItem you could render a clickable <span>, and attach any logic you like to the click event.

If you go that route, you may have a need to turn OFF the default click action. I think autocomplete uses an <a> for the element that provides the click event. In that case, you'll need to unset that click handler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...