jQuery的one()函数会杀死一切

one() function of jQuery kills everything

本文关键字:函数 one jQuery      更新时间:2023-09-26

我正试图像谷歌一样制作一个自动完成列表。当你键入一些内容时,它会为你建议一些单词,当你按下向下按钮时,你所在的元素会变成蓝色。

以下是一个显示该问题的JSFiddle。每次,当我按下向下按钮时,只有一个元素必须是蓝色的,但在这里它不起作用。

这个代码出了什么问题?

$(".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");
        }
    }
})

我尝试了jQuery的one("keydown", function() {})函数而不是keydown(function() {})函数,但它不起作用。我该怎么办?

尝试自己学习如何做到这一点很好,但既然你用jQuery标记了你的问题,你知道有一个jQuery UI插件可以处理自动完成吗?它非常健壮,可以处理从Ajax返回的JSON等。

这是插件的演示页面,还有文档。

为了便于说明,下面是演示页面上显示的非常简单的示例的代码。它从硬编码列表中填充控件,这可能不太可能是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>

其中的关键部分是极其简单的控制接线:

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

即使你选择不使用该插件,你也可以从阅读如何自动完成的底层代码中得到一个好主意。

我还将注意到,当你在谷歌上搜索时,知道这一点可能会有所帮助,这一功能通常也被称为"自动建议"。

您的代码无法工作的原因是这一行已损坏。

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

它无法工作,因为find("li")将返回一个包含4 li的数组。您应该将[style]添加到选择器中,以仅选择具有样式集的数组。

我的JSFiddle在修复了那条线后:http://jsfiddle.net/Sn9V8/2/

不管怎样,我建议你两件事:

  • 使用类,而不是每次都应用样式。代码看起来会越来越简单
  • 看看其他人提到的插件。他们有很棒的文档和社区的支持,所以他们会加快你的开发

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

attr将始终是一个jQuery对象,即使它没有找到元素。因此,在您的下一行中,typeof attr !== 'undefined'将始终为真。


请参阅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');
    }
})

我宁愿依赖类来实现这一点,而不是读取内联样式。

小提琴

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');
});