【问题标题】:Search function in HTML using JavaScript [closed]使用 JavaScript 在 HTML 中搜索功能 [关闭]
【发布时间】:2015-12-08 10:51:40
【问题描述】:

我曾尝试使用 Javascript 创建搜索功能,但它不起作用。

function contains(text_one, text_two) {
    if (text_one.indexof(text_two) != -1)
        return true;
}

$("#searchText").onkeyup(function(){
    var searchText = $("searchText").val().toLowerCase()
    $("ul li").each(function() {
        if (!contains($(this).text().toLowerCase(), searchText))
            $(this).hide();
        else
            $(this).show();
    });
});

【问题讨论】:

  • 请给我们您的 HTML、CSS(如果有的话)和 JavaScript。还要告诉你,你想达到什么目标,什么是行不通的。

标签: javascript jquery html search


【解决方案1】:

您可以使用开发者控制台自行调试所有这些问题。如果您在浏览器中按 F12,您将能够看到您的 JS 代码引发的所有错误并解决它们。

从上面我可以看出你的代码有几个问题:

  • 你应该使用indexOf,而不是indexof,因为JS是区分大小写的
  • $('searchText') 选择器缺少 id 前缀:$('#searchText')
  • jQuery 没有onkeyup 方法,只有keyup

还请注意,您可以通过使用toggle() 并在contains() 函数中仅返回indexOf 比较的结果来改进逻辑。试试这个:

function contains(text_one, text_two) {
    return text_one.toLowerCase().indexOf(text_two.toLowerCase()) != -1;
}

$("#searchText").keyup(function(){
    var searchText = $(this).val();
    $("ul li").each(function() {
        $(this).toggle(contains($(this).text(), searchText));
    });
});

Example fiddle

【讨论】:

  • ty,我解决了,你真好~~xd
  • 很高兴为您提供帮助。不要忘记投票并接受答案。
猜你喜欢
  • 2013-03-14
  • 1970-01-01
  • 2012-11-28
  • 2016-01-26
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 2020-08-13
  • 2015-04-06
相关资源
最近更新 更多