在原版 JavaScript 中点击获取更多数据



我提供了更多信息来澄清我遇到的问题。

我的目的是创建一个加载更多按钮。单击时,页码应动态递增。如何在每次单击按钮时将函数incrementPage()的结果放入api.pageNum中?catchInput()getResults()我也用它来获取输入数据。

单击按钮后,从输入中获取的数据伴随着从按钮单击中获取的数据。

import './styles.css';
import _ from 'lodash';
import template from './templates/template.hbs';
const api = {
key: '###',
querySearch: '',
pageNum: 1,
};
const refs = {
list: document.querySelector('.gallery'),
form: document.querySelector('#search-form'),
input: document.querySelector('input'),
button: document.querySelector('button'),
};
refs.input.addEventListener('input', _.debounce(catchInput, 700));
function catchInput() {
getResults(refs.input.value);
}
function incrementPage() {
api.pageNum += 1;
}
function getResults(querySearch) {
refs.list.innerHTML = '';
if (querySearch.length > 0) {
fetch(
`https://pixabay.com/api/?image_type=photo&orientation=horizontal&q=${querySearch}&page=${api.pageNum}&per_page=12&key=${api.key}`,
)
.then(response => {
if (response.ok) return response.json();
throw new Error(
`${response.status} error while your search has occured`,
);
})
.then(pic => {
const info = pic.hits.map(item => template(item)).join('');
refs.list.insertAdjacentHTML('beforeend', info);
})
.catch(err => {
throw err;
});
incrementPage();
}
}
refs.button.addEventListener('click', catchInput);

.html

<body>
<form class="search-form" id="search-form">
<input
type="text"
name="query"
autocomplete="off"
placeholder="Search images..."
/>
</form>
<ul class="gallery"></ul>
<button class="btn-primary is-hidden" data-action="load-more">
Load more
</button>

如果我理解正确,如果你想获取当前页码,你可以使用这种方法代替你的:

let url = window.location.href;
let pageNum = url[url.indexOf("&page=") + 6];
console.log(pageNum);

最新更新