用JS进行搜索

时间:2019-03-13 08:39:02

标签: javascript

我想搜索,但是我有问题。它向我显示“未定义CurentElement” ...您能帮我吗

$("#searchForm").submit(function(e) {
    e.preventDefault();

    let matches = [ ];
    let searchText = $("#searchText").val();
    for (let i = 0; i < products.lenght; i++) {
        let currentProduct = products[i];
        let nameTolower = currentProduct.name.toLowerCase();
        let isMatch = nameToLower.indexOf(searchText) >= 0;
        if(isMatch){
            matches.push(currentProduct)
         };
    };
        appendProducts(matches);

});

1 个答案:

答案 0 :(得分:0)

如果可以的话,首先快速解决两个问题,它是products.length而不是products.lenght,并且在您实例化此变量nameTolower之后,但您随后调用了nameToLower,有一个'L'上的大写字母:)

由于这两行,我认为您的产品是一个对象数组:

let currentProduct = products[i];
let nameTolower = currentProduct.name.toLowerCase();

所以我要清空结果标签,然后用您的函数查看名称是否匹配,然后附加数据。 如果您在输入为空的情况下提交,它将显示所有产品。

const products = [
  {name: "First", price: 25, quantity: 5}, 
  {name: "Second", price: 10, quantity: 3}
];

$("#searchForm").submit(function(e) {
    e.preventDefault();
    // Empty HTML tag first
    $('#results').empty();
    let matches = [];
    let searchText = $("#searchText").val().toLowerCase(); // toLowerCase() because you're checking nameToLower just after
    for (let i = 0; i < products.length; i++) {
        let currentProduct = products[i];
        let nameToLower = currentProduct.name.toLowerCase();
        let isMatch = nameToLower.indexOf(searchText) >= 0;
        if(isMatch){
            matches.push(currentProduct)
         }
    }
   matches.forEach(function(match){
   	$('#results').append("<ul><li>" + match.name + "</li><ul><li>Price : " + match.price + "</li><li>Quantity : " + match.quantity + "</li></ul></ul>");
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="searchForm">
  <input type="text" id="searchText" />
  <button type="submit">
    Submit
  </button>
</form>

<div id="results">

</div>

那回答了你的问题吗? 希望对您有帮助!