简体   繁体   中英

How to trigger javascript generated HTML list items with return key stroke

I've just implemented a Javascript autocomplete search box inside my website, but the only way I can trigger the links to sub pages is by clicking list items with my mouse. What I want to do, in add to the possibility to select with keyboard that's already implemented, the possibility to hit "return" key on keyboard and go to the selected landing page.

The Js I'm using is:

<script>
$(function() {
var projects = [
  {
    value: "value1",
    label: "value1",
    desc: "descr1",
    icon: "icon1.png",
link: "http://url1"
  },
  {
    value: "value2",
    label: "value2",
    desc: "descr2",
    icon: "icon2.png",
link: "http://url2"
  }
];

$( "#project" ).autocomplete({
  minLength: 2,
  source: projects,
  focus: function( event, ui ) {
    $( "#project" ).val( ui.item.label );
    return false;
  },
  select: function( event, ui ) {
    $( "#project" ).val( ui.item.label );
    $( "#project-id" ).val( ui.item.value );
    $( "#project-description" ).html( ui.item.desc );
    $( "#project-icon" ).attr( "src", ui.item.icon );
    return false;
  }
})

.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
  return $( "<li>" )
    .append( "<a href='" + item.link + "'>" + "<img style='height:35px;' src='" + item.icon + "'/>" + "  " + item.label + " - " + item.desc + "</a>" )
    .appendTo( ul );
};
});
</script>

The HTML I'm using is:

<input id="project"></div>

You can see an example here: http://www.lolgame.it/lolgame-counterpicks/

Thanks a lot everyone

Heere we go. Tested here: http://jsfiddle.net/agWH2/

$( "#project" ).autocomplete({
      minLength: 1,
      source: projects,
      focus: function( event, ui ) {
        $( "#project" ).val( ui.item.label );
        return false;
      },
      select: function( event, ui ) {
        if (event.keyCode == 13) {
          window.location.href = ui.item.link;
        }
        $( "#project" ).val( ui.item.label );
        $( "#project-id" ).val( ui.item.value );
        $( "#project-description" ).html( ui.item.desc );
        $( "#project-icon" ).attr( "src", ui.item.icon );
        return false;
      }
    })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<a href='" + item.link + "'>" + "<img style='height:35px;' src='" + item.icon + "'/>" + "  " + item.label + " - " + item.desc + "</a>" )
        .appendTo( ul );
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM