简体   繁体   English

jQuery的one()函数杀死所有内容

[英]one() function of jQuery kills everything

I am trying to make an autocomplete list like Google does. 我正在尝试像Google一样列出自动填充列表。 When you type something it will suggest some words for you and when you press the down button the element you are on becomes blue. 当您键入内容时,它会为您提示一些单词,并且当您按下向下按钮时,您所在的元素将变为蓝色。

Here is a JSFiddle that shows the issue. 这是显示问题的JSFiddle Every time, when I press the down button, just one element must be blue but in here it doesn't work. 每次,当我按下向下按钮时,只有一个元素必须是蓝色,但是在这里它不起作用。

What's wrong in this code? 这段代码有什么问题?

$(".search").keydown(function(e) {
    if (e.keyCode == 40) {
        var attr = $("#showlist").find("li").attr("style");
        if (typeof attr !== 'undefined' && attr !== false){
            var stylist = $("#showlist").find("[style]");
            stylist.removeAttr("style");
            stylist.next().attr("style","background-color:blue");
        } else {
            $("#showlist li:first-child").attr("style", "background-color:blue");
        }
    }
})

I have tried the one("keydown", function() {}) instead of keydown(function() {}) function of jQuery but it didn't work. 我尝试了jQuery的one("keydown", function() {})而不是keydown(function() {})函数,但是没有用。 What should I do? 我该怎么办?

It's good to try to learn how to do this on your own, but since you tagged your question with jQuery, are you aware that there is a jQuery-UI plugin that handles autocomplete? 尝试自己学习如何做是一件好事,但是由于您使用jQuery标记了问题,因此您是否知道有一个可处理自动完成功能的jQuery-UI插件? It is quite robust and can handle JSON and such returned from Ajax. 它非常健壮,可以处理JSON等从Ajax返回的信息。

Here's the demo page for the plugin, and here's the documentation . 这是插件的演示页面 ,还有文档

For the sake of illustration, here is the code for the very simple example shown on that demo page. 为了便于说明,下面是该演示页面上显示的非常简单示例的代码。 It populates the control from a hard-coded list, which may be unlikely IRL. 它从硬编码列表填充控件,这不太可能是IRL。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
  </script>
</head>
<body>
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>
</body>
</html>

The key part in there is the exceedingly simple wiring up of the control: 其中的关键部分是控制极其简单的接线:

 $( "#tags" ).autocomplete({
      source: availableTags
    });

Even if you elect not to use that plugin, you might get a good idea from reading the underlying code of how to do your autocomplete. 即使您选择不使用该插件,也可以通过阅读有关如何完成自动完成的基本代码来获得一个好主意。

I will also note that it may be helpful to know as you are googling around, this functionality is also often referred to as "autosuggest". 我还将注意到,在您四处搜寻时可能会有所帮助,此功能通常也称为“自动建议”。

The reason your code is not working is because this line is corrupted. 您的代码无法正常工作的原因是因为此行已损坏。

var attr = $("#showlist").find("li").attr("style");

It can't work as find("li") will return an array with 4 li in it. 它无法工作,因为find(“ li”)将返回其中包含4 li的数组。 You should add [style] to the selector to select only that with the style set. 您应将[style]添加到选择器中,以仅选择设置了样式的样式。

My JSFiddle after fixing that line: http://jsfiddle.net/Sn9V8/2/ 修复该行后,我的JSFiddle: http : //jsfiddle.net/Sn9V8/2/

Anyway, I would suggest you two things: 无论如何,我建议您两件事:

  • Use classes instead of applying style's everytime. 使用类而不是每次都应用样式。 The code will look easier and simpler. 该代码将看起来更简单。
  • Take a look at the plugins mentioned by the others. 看看其他人提到的插件。 They have great docs and support from the community, so they will speed up your development. 他们在社区中提供了出色的文档和支持,因此将加快您的开发速度。

In your code you have, var attr = $("#showlist").find("li").attr("style"); 在您的代码中, var attr = $("#showlist").find("li").attr("style");

attr will always be a jQuery object even if it doesn't find the element. 即使找不到元素, attr仍将始终是jQuery对象。 So in your next line typeof attr !== 'undefined' will always be true. 因此,在您的下一行中, typeof attr !== 'undefined'将始终为true。


See Fiddle for a quick update to your issue. 有关问题的快速更新,请参阅Fiddle

$(".search").keydown(function (e) {

    // Up
    if (e.keyCode == 38) {
        var $active = $("#showlist li.active");

        if ($active.length){
            if ($active.prev('li').length)
               $active.removeClass('active').prev('li').addClass('active');
        }
        else 
            $("#showlist li:first-child").addClass('active');
    }

    // Down
    if (e.keyCode == 40) {
        var $active = $("#showlist li.active");

        if ($active.length){
            if ($active.next('li').length)
               $active.removeClass('active').next('li').addClass('active');
        }
        else 
            $("#showlist li:first-child").addClass('active');
    }
})

I would rather rely on classes for this instead of reading inline styles. 我宁愿依靠类来代替读取内联样式。

FIDDLE 小提琴

var $items = $('#showlist li'),
    $selectedItem = $items.find('.selected'),
    lastIndex = $items.length - 1,
    selectedIndex = -1;

$(".search").keydown( function(e) {

    var key = e.which,
        down = key === 40;

    if (!down && key !== 38) return;

    selectedIndex += down? 1 : -1;

    if (selectedIndex < 0 || selectedIndex > lastIndex) 
        selectedIndex = down? 0 : lastIndex;

    $selectedItem.removeClass('selected');

    $selectedItem = $($items[selectedIndex]).addClass('selected');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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