[英]How to add 'load more' functionality to items on a page with vanilla JS?
[英]load 3 more items [JS]
我試圖理解這些基本定義功能的 JS 代碼字符串,一旦單擊按鈕,頁面上就會加載 3 個其他元素(如果有的話)。
雖然我已經閱讀了文檔,但我不明白這一行
boxes[i].style.display = 'inline-block';
這是完整的代碼
let loadMoreBtn = document.querySelector('.packages .load-more .btn'); //seleziono il primo elem con questa classe let currentItem = 3; // # offerte caricate dopo il click loadMoreBtn.onclick = () =>{ let boxes = [...document.querySelectorAll('.packages .box-container .box')]; //salvo in boxes tutti gli elem che hanno questa classe for (var i = currentItem; i < currentItem + 3; i++){ boxes[i].style.display = 'inline-block'; }; currentItem += 3; if(currentItem >= boxes.length){ loadMoreBtn.style.display = 'none'; }
您提供的行是使用 javascript 修改元素的 CSS 屬性。 如果您對不同的顯示選項感興趣,請查看CSS 顯示語法。
所以基本上你的代碼片段做了什么:當你點擊加載更多按鈕時,它會在列表中的接下來的 3 個框上設置display: inline-block
。 如果沒有更多的框,加載更多按鈕將被隱藏( display: none
)
首先要注意的是,您在for-loop中運行代碼,該循環用於逐個迭代元素。 boxes[i]
是循環中該點被引用的元素。
'element.style.display' 部分正在設置該元素的CSS 屬性。 在這種情況下,它將display
屬性設置為'inline-block' ,這將使元素並排顯示(可能與'block'相對,這會使新元素顯示在block
下方'編輯項目)。
通過在大多數行之前添加注釋,我已經對下面發生的事情進行了細分:
// Grab the clickable button.
let loadMoreBtn = document.querySelector('.packages .load-more .btn');
// We start counting from the third item. I guess we're assuming some items
// are already visible?
let currentItem = 3;
// This function is called when the button is clicked.
loadMoreBtn.onclick = () => {
// This find all elements that match the classes 'packages', 'box-container', and 'box'
const allElements = document.querySelectorAll('.packages .box-container .box');
// This is using a spread operator to place our elements inside an array.
let boxes = [ ...allElements ];
// Loop through all the items we matched using querySelectorAll above. We
// start counting at whatever `currentItem` is. The loop will keep running
// until `i` is 3 less than `currentItem` (or not loop at all if that
// condition is already met).
for (let i = currentItem; i < currentItem + 3; i++) {
// Display the element.
boxes[i].style.display = 'inline-block';
}
currentItem += 3;
if (currentItem >= boxes.length) {
// Hide the button if there are no more elements to loop through.
loadMoreBtn.style.display = 'none';
}
// [...]
它基本上將該元素的display
屬性設置為inline-block
。 這可以使用 CSS(通過設置display: inline-block;
)或使用 JavaScript 通過將element.style.display
屬性設置為inline-block
來完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.