【问题标题】:How do i remove the items from the searched list once the entire text is removed from the search textBox using JQuery使用 JQuery 从搜索文本框中删除整个文本后,如何从搜索列表中删除项目
【发布时间】:2017-11-23 07:38:29
【问题描述】:

我已经使用 Jquery 和 JSON 实现了实时搜索。最初没有结果显示,因为搜索框中没有文本。当我在搜索文本框中写一些文本时,它会显示结果。但是,即使我从搜索文本框中删除了文本,也会显示结果。

从文本框中删除所有内容后,如何删除结果?

以下是jquery代码:

$('#search').keyup(function(){
  var searchField= $('#search').val();
  console.log(searchField);
  var myExp = new RegExp(searchField, "i" );
  $.getJSON('js/data.json', function(data){
    var output = '<ul class="seachresults">';
    $.each(data, function(key,val){
      if((val.name.search(myExp)!= -1) || (val.company.search(myExp)!= -1)){
      output += '<li>';
      output += '<h2>'+ val.name +'</h2>';
      output += '<img src="images/'+val.shortname+'_tn.png" alt="'+val.name+ '" />'  ;
      output += '<p>'+ val.description +'</p>';
      output += '<h2>'+ val.company +'</h2>';
      output += '<h2>'+ val.price +'</h2>';
      output += '</li>';
    }
    });
    output+= '</ul>';
    $('#update').html(output);
  });

});

以下是 HTML 代码:

<div id='searcharea'>
  <label for="search">Product Directory</label>
  <p>Search</p>
  <input type="search" name="search" id="search" placeholder="info" />
</div>
<div id='update'></div>

【问题讨论】:

    标签: jquery json livesearch


    【解决方案1】:

    您检查是否使用if ($.trim(searchField) != '') { 输入了一些值。如果有一些值,则现有代码将起作用,否则它将清除结果容器。所以你在if 条件之外初始化var output = '';。

    以下更新代码:

    $('#search').keyup(function() {
      var searchField = $(this).val();
      console.log(searchField);
      var myExp = new RegExp(searchField, "i");
      var output = '';
      if ($.trim(searchField) != '') {
        $.getJSON('js/data.json', function(data) {
          output = '<ul class="seachresults">';
          $.each(data, function(key, val) {
            if ((val.name.search(myExp) != -1) || (val.company.search(myExp) != -1)) {
              output += '<li>';
              output += '<h2>' + val.name + '</h2>';
              output += '<img src="images/' + val.shortname + '_tn.png" alt="' + val.name + '" />';
              output += '<p>' + val.description + '</p>';
              output += '<h2>' + val.company + '</h2>';
              output += '<h2>' + val.price + '</h2>';
              output += '</li>';
            }
          });
          output += '</ul>';
        });
          $('#update').html(output);
      } else {
          $('#update').html(output);
      }
    });
    

    【讨论】:

    • $('#update').html(output) 也需要添加到 if 循环中。休息它的工作正常。谢谢
    • $('#update').html(output); 在if 循环之外/之后。这意味着,它将始终获得在output 变量中设置的正确值。
    • 但是使用上面的代码,如果我在搜索框中输入内容,我看不到任何结果
    • 当我在output += '&lt;/ul&gt;'; 之后添加$('#update').html(output);,它工作正常
    猜你喜欢
    • 2010-11-26
    • 2016-01-21
    • 1970-01-01
    • 2012-11-25
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多