Javascript 在jqueryequals选择器中使用变量?
我正在尝试使用JQuery的Javascript 在jqueryequals选择器中使用变量?,javascript,jquery,list,Javascript,Jquery,List,我正在尝试使用JQuery的not选择器和带有变量的eq选择器来根据搜索条件过滤项目列表 我有一份产品清单和一份价格清单。我也有一个搜索字段,你可以在这里搜索产品或价格。我的目标是,当有人搜索特定产品时,只显示该产品,隐藏其余产品 这是我的密码 var numItems = 5; // When the search button is clicked $("#search-btn").click(function() { // As long as the search fi
not
选择器和带有变量的eq
选择器来根据搜索条件过滤项目列表
我有一份产品清单和一份价格清单。我也有一个搜索字段,你可以在这里搜索产品或价格。我的目标是,当有人搜索特定产品时,只显示该产品,隐藏其余产品
这是我的密码
var numItems = 5;
// When the search button is clicked
$("#search-btn").click(function() {
// As long as the search field has a value
if ($("#search-field").val() !== "") {
var productsArray = [];
for (var i = 0; i < numItems; i++) {
// If the product name equals the search field value add to
// the array
if (products[i] == $("#search-field").val()) {
productsArray.push(products[i]);
}
}
// Get the index of the product
var pos = products.indexOf(productsArray[0]);
$("#products-list > li:not(:eq(pos - 1)),
#price-list > li:not(:eq(pos - 1))").hide();
}
});
#产品列表
和#价格列表
分别是我的产品列表和价格列表的名称。我正在使用直接子选择器>
查找这些列表的所有列表元素。然后,我尝试选择与搜索条件不匹配的列表项并将其隐藏。这样,只显示搜索列表项
我需要知道如何在jquery选择器中放置变量。在我看来,您只需要使用串联器:
$("#products-list > li:not(:eq(" + (pos - 1) + ")), #prices-list > li:not(:eq(" + (pos - 1) + "))").hide();
希望这有帮助
$(“#产品列表>li:not(:eq(+(pos-1)+)”),#价格列表>li:not(:eq(+(pos-1)+)”).hide()代码>我知道应该这样做,但这是一个非常简单的问题,我觉得没有必要解释我的答案,所以我使用了注释。jQuery选择器只是一个字符串。使用字符串连接。在pos-1
周围添加括号,否则您将评估类似“#products list>li:not(:eq(0)-1
)的内容。我知道这一点的原因是:如果它是字符串的一部分,通常情况并非如此,但无论如何,我都喜欢这样做。
$("#products-list > li:not(:eq(" + (pos - 1) + ")), #prices-list > li:not(:eq(" + (pos - 1) + "))").hide();