如何在keyup上显示搜索结果?

发布于 2024-11-09 10:20:32 字数 2306 浏览 0 评论 0原文

我有一个搜索框,当用户在搜索框中输入字母时,我们将过滤并显示结果。然而,当用户键入每个字母时,搜索结果会在显示和隐藏之间切换。我对 JS 很陌生,所以我希望它可以是一个简单的修复。

这是我的 HTML:

See Below

这是我的切换 JS:

See Below

如何调整 JS 不来回切换?

//这是我的编辑,以帮助回答这个问题。这是我用来显示结果的 JS 和 HTML:

HTML:

<div class="friendssearch" onclick="toggle_visibility('friendslist');">
  <div class="friendssearch">
    <div id="friendssearchbox"></div>
  </div>
        <ul id="friendslist" style="display: none;">
            <li>
              <a href="#">  
                <div class="friendsflybox" title="Friends Name">
                    <p class="friendsflyboxname">Ryan Bennett</p>
                </div>
              </a>
            </li>
        </ul>
    </div>

Javascript:

<script> 
(function ($) {
 // custom css expression for a case-insensitive contains()
 jQuery.expr[':'].Contains = function(a,i,m){
   return (a.textContent || a.innerText || 
"").toUpperCase().indexOf(m[3].toUpperCase())>=0;
 };

 function listFilter(header, list) { // header is any element, list is an unordered list
 // create and add the filter form to the header
 var form = $("<form>").attr({"class":"filterform","action":"#"}),
    input = $("<input>").attr({"class":"filterinput clearFieldBlurred  
ClearField","type":"text", "value":"Start typing a Name"});
$(form).append(input).appendTo(header);

$(document).ready(function() {
$('.clearField').clearField();
}); 

$(input)
  .change( function () {
    var filter = $(this).val();
    if(filter) {
      // this finds all links in a list that contain the input,
      // and hide the ones not containing the input while showing the ones that do
      $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
      $(list).find("a:Contains(" + filter + ")").parent().slideDown();
    } else {
      $(list).find("li").slideDown();
    }
    return false;
  })
.keyup( function () {
    // fire the above change event after every letter
    $(this).change();
});
} 
//ondomready
$(function () {
  listFilter($("#friendssearchbox"), $("#friendslist"));
});
}(jQuery));
</script> 

I have a search box that as the user types letters into the search box, we will filter and display the results. However, as the user types each letter the search results are getting toggled between showing and hiding. I am very new to JS so I hope it could be an easy fix.

Here is my HTML:

See Below

Here is my toggle JS:

See Below

How can I tweak the JS to not toggle back and forth?

//Here are my edits to help answer the question. This is the JS and HTML I am using to display the results:

HTML:

<div class="friendssearch" onclick="toggle_visibility('friendslist');">
  <div class="friendssearch">
    <div id="friendssearchbox"></div>
  </div>
        <ul id="friendslist" style="display: none;">
            <li>
              <a href="#">  
                <div class="friendsflybox" title="Friends Name">
                    <p class="friendsflyboxname">Ryan Bennett</p>
                </div>
              </a>
            </li>
        </ul>
    </div>

Javascript:

<script> 
(function ($) {
 // custom css expression for a case-insensitive contains()
 jQuery.expr[':'].Contains = function(a,i,m){
   return (a.textContent || a.innerText || 
"").toUpperCase().indexOf(m[3].toUpperCase())>=0;
 };

 function listFilter(header, list) { // header is any element, list is an unordered list
 // create and add the filter form to the header
 var form = $("<form>").attr({"class":"filterform","action":"#"}),
    input = $("<input>").attr({"class":"filterinput clearFieldBlurred  
ClearField","type":"text", "value":"Start typing a Name"});
$(form).append(input).appendTo(header);

$(document).ready(function() {
$('.clearField').clearField();
}); 

$(input)
  .change( function () {
    var filter = $(this).val();
    if(filter) {
      // this finds all links in a list that contain the input,
      // and hide the ones not containing the input while showing the ones that do
      $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
      $(list).find("a:Contains(" + filter + ")").parent().slideDown();
    } else {
      $(list).find("li").slideDown();
    }
    return false;
  })
.keyup( function () {
    // fire the above change event after every letter
    $(this).change();
});
} 
//ondomready
$(function () {
  listFilter($("#friendssearchbox"), $("#friendslist"));
});
}(jQuery));
</script> 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

星軌x 2024-11-16 10:20:32

您需要执行类似于我在下面发布的代码的操作。这假设您可以访问包含搜索结果的对象。

function toggle_visibility(id)
{
    //Check if there are any search results to display
    var searchResultLength = document.getElementById(searchResultID).innerHTML.length;

    if (searchResultLength > 0) // display div
    {
        var e = document.getElementById(id);
        e.style.display = 'block';
    }
    else //No search results, hide div
    {
        e.style.display = 'none';
    }
}

基本上,您需要在尝试切换 div 的可见性之前确定是否有要显示的搜索结果。

//在评论后编辑

好的,所以看起来结果是将 li 添加到 ul 中。因此,假设代码删除并添加了 li,您应该检查 ul == 0 中的元素数量。请参见下文。

$('#friendslist > li').length

老实说,我在尝试确定代码的确切内容时遇到了一些困难
正在做。我当然不是 jquery 专家。我想说,如果上面的代码不能让你朝着正确的方向前进,我就没有主意了。

You'll need to do something similar to the code I have posted below. This assumes that you can access the object that contains the search results.

function toggle_visibility(id)
{
    //Check if there are any search results to display
    var searchResultLength = document.getElementById(searchResultID).innerHTML.length;

    if (searchResultLength > 0) // display div
    {
        var e = document.getElementById(id);
        e.style.display = 'block';
    }
    else //No search results, hide div
    {
        e.style.display = 'none';
    }
}

Basically, you need to determine if you have search results to display before you attempt to toggle the div's visibility.

//EDIT AFTER COMMENTS

OK, so it looks like the results are adding li's to the ul. So, assuming that the code is taking away the li's as well as adding them, you should be checking for the number of elements in the ul == 0. See below.

$('#friendslist > li').length

To be honest, I'm having a bit of difficulty trying to determine exaclty what the code is
doing. I'm certainly not a jquery expert. I would say if the above code doesn't get you going in the right direction, I'm out of ideas.

橪书 2024-11-16 10:20:32

如果您只想在输入字段时显示它,请使用 onFocus="method()" 属性。接下来是 onBlur="method()"。这将在您进入该字段时显示该块,并在您离开该字段时隐藏它。

<input id="searchbox" type="text" onFocus="toggle_visibility('friendslist');" onBlur="toggle_visibility('friendslist')">

<ul id="friendslist" style="display: none;">
  <!--search results HTML-->
</ul>

授人以鱼:http://www.w3schools.com/jsref/dom_obj_event.asp

// 编辑

我认为 Quickfire 的答案是最好的解决方案。但据我了解,您希望显示/隐藏结果,因此我修改了他的方法以更好地适合您的标记。

function toggle_visibility(id){

    //Get the total number of <li> within my search result
    var results=document.getElementById(searchResultID).childNodes.length;

    if (results > 0){ // we have more than 0 results
        var e = document.getElementById(id);
        e.style.display = 'block'; // show the element
    }else{ //No search results, hide div

        e.style.display = 'none'; //hide the element
    }
}

If you're only wanting it to display when you enter the field use the onFocus="method()" attribute. followed by onBlur="method()". this will display the block when you enter the field and hide it when you leave.

<input id="searchbox" type="text" onFocus="toggle_visibility('friendslist');" onBlur="toggle_visibility('friendslist')">

<ul id="friendslist" style="display: none;">
  <!--search results HTML-->
</ul>

teach a man to fish: http://www.w3schools.com/jsref/dom_obj_event.asp

// EDIT

I think Quickfire's answer is the best solution. but as I understand it you want you results to show/hide, so I modified his method to better suit your markup.

function toggle_visibility(id){

    //Get the total number of <li> within my search result
    var results=document.getElementById(searchResultID).childNodes.length;

    if (results > 0){ // we have more than 0 results
        var e = document.getElementById(id);
        e.style.display = 'block'; // show the element
    }else{ //No search results, hide div

        e.style.display = 'none'; //hide the element
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文