我想在input
html元素上使用keyup事件进行过滤:当用户输入内容时,我想只显示包含“蛋白质”名称的div
元素。
带有“elementsName”类的div
是包含这些蛋白质名称的元素; .theMainSectionInTheModalBody
是一个div
元素。
我知道列表元素要容易得多,但我必须使用div
,因为将元素(图像,文本等)放在一个列表元素中很难。
qazxsw poo只是一个对象数组,其中输入了所有元素。
proteins
这是HTML代码:
const theLookOfTheProteinsInTheModalBody = () =>
{
for(let elements of proteins) {
$('.theMainSectionInTheModalBody').append
(`
<div class="calculatorBox">
<span class="openTheDescriptionText">+</span>
<div class="elementsName">${ elements.name } <span>${ elements.price }</span></div>
<span><img class="small" src=${elements.image} /></span>
</div>
<div class="panel">
<p class="calculatorBoxText">${elements.text}</p>
</div>
`)
}
}
我建议对数组执行过滤和排序,而不是直接对DOM元素执行过滤和排序。通过稍加修改,您可以使用现有函数根据筛选/排序数组重新填充列表:
比<div class="modal-header">
<span class="closeTheModalBox">×</span>
<h3>Your current sum from the shopping</h3>
<input type="text" id="filter" />
<button class="sortByHighestPrices">Sort the prortein by the highest price</button>
<button class="sortByLowestPrices">Sort the prortein by the lowest price</button>
<div id="sum"></div>
</div>
<div class="modal-body">
<div class="theMainSectionInTheModalBody"></div>
</div>
事件更好地使用input
事件。同时将单击处理程序绑定到按钮,并在调用常见的keyup
函数之前让这些按钮首先对原始proteins
数组进行排序。然后,后一个函数应该应用过滤器并将过滤后的数组传递给您拥有的函数(上面的更改):
refresh
const theLookOfTheProteinsInTheModalBody = (proteins) => { // pass the argument
$('.theMainSectionInTheModalBody').empty(); // <-- clear list before populating
for(let elements of proteins) {
$('.theMainSectionInTheModalBody').append(`
<div class="calculatorBox">
<span class="openTheDescriptionText">+<\/span>
<div class="elementsName">${ elements.name } <span>${ elements.price }<\/span><\/div>
<span><img class="small" src="${elements.image}" /><\/span>
<\/div>
<div class="panel">
<p class="calculatorBoxText">${elements.text}<\/p>
<\/div>
`);
}
};
// Sample data
var proteins = [{
name: "banana",
price: 12.33,
image: "test.img",
text: "they are yellow"
}, {
name: "apple",
price: 9.25,
image: "test.img",
text: "one apple a day..."
}];
function refresh() {
const find = $("#filter").val();
// Only pass filtered list to display function:
theLookOfTheProteinsInTheModalBody(proteins.filter(elem => elem.name.includes(find)));
}
// Use input event (not keyup)
$("#filter").on("input", refresh);
$(".sortByHighestPrices").click(() => {
proteins.sort((a,b) => b.price - a.price);
refresh();
});
$(".sortByLowestPrices").click(() => {
proteins.sort((a,b) => a.price - b.price);
refresh();
});
refresh();
.elementsName{ display: inline-block }
.small { width: 20px; height: 20px }