2013-08-18 3 views
1

내 JQuery와 모바일 페이지에 검색 기능을 만들려고 노력하고,검색 상자 jQuery를 모바일

HTML은 :

<input type="search" placeholder="Search" id="searchbar" /> 
    <ul data-role="listview" id="searchlist"></ul> 

사용자가 검색되기 때문에, 결과는리스트 뷰에 추가됩니다.

검색 창에 글자를 입력 할 때마다 다음 코드를 실행하고 싶습니다. 어떻게해야합니까?

if (searchbar.val().length > 2) 
    { 
     $.ajax({ 
      url: "http://clubbedin.zymichost.com/search.php", 
      type: "post", 
      crossDomain: true, 
      data: { 
       'q': value, 
       'userID': userID 
      }, 
      success: function(data) { 
       var json = jQuery.parseJSON(data); 
       for (var i = 0; i < json.length; i ++) 
       { 
        html += '<li><a data-option-id=\"' + json[i].optionid + '\">' + json[i].optionname + '</a></li>'; 
       } 
       $('searchlist').append(html); 
       $('searchlist').listview("refresh"); 
      } 
     }); 
    } 

도움이 되겠습니다. 감사!

답변

1

이 경우 keypress 이벤트를 사용할 수 있습니다.

$(document).on("keypress", "#searchbar", function (e) { 
var searchbar = $(this); 
//your code 
}); 

또는 당신은 input 이벤트 핸들러를 사용할 수 있습니다. 즉,이 링크를 참조하는 방법에 대한 추가 정보를 원하시면 : http://www.raymondcamden.com/index.cfm/2012/3/27/Example-of-Autocomplete-in-jQuery-Mobile

는 기본적으로이 같은 갈 것 :

$(document).on("input", "#searchbar", function (e) { 
    //your code 
    }); 

또 다른 방법 (아마도 가장 좋은 방법을) JQM 붙박이 장치를 사용하는 것 원격 데이터를로드합니다. Here's a demo of that. The source code is also provided here. 기본적으로 listviewbeforefilter 이벤트를 사용하면 ajax을 호출하는 모든 코드를 넣을 수 있습니다.

+0

작품을 마법처럼, 덕분에 다시 한번 @hungerpain – nshah

0

당신은 사용할 수 있습니다

$("#searchlist").on("listviewbeforefilter", function (e, data) { 
    var $ul = $(this), 
    $input = $(data.input), 
    value = $input.val(), 
    html = ""; 
    if (value && value.length > 2) { 
    $.ajax({ 
     url: "http://clubbedin.zymichost.com/search.php", 
     type: "post", 
     crossDomain: true, 
     data: { 
      'q': value, 
      'userID': userID 
     }, 
     success: function(data) { 
      var json = jQuery.parseJSON(data); 
      for (var i = 0; i < json.length; i ++) 
      { 
       html += '<li><a data-option-id=\"' + json[i].optionid + '\">' + json[i].optionname + '</a></li>'; 
      } 
      $ul.html(html); 
      $ul.listview(); 
      $ul.listview("refresh"); 
      $ul.trigger("updatelayout"); 
     } 
    }); 
    } 
});