我有一个HTML代码块:
<div class="row" data-aos="fade-up">
<div class="col-lg-12 d-flex justify-content-center">
<ul id="portfolio-flters">
<li data-filter=".filter-journal">Journal articles</li>
<li data-filter=".filter-wp">Working papers</li>
<li data-filter=".filter-conferences">Conferences</li>
</ul>
</div>
</div>
这个JavaScript函数点击<li>
:
window.addEventListener('load', () => {
let portfolioContainer = select('.portfolio-container');
if (portfolioContainer) {
let portfolioIsotope = new Isotope(portfolioContainer, {
itemSelector: '.portfolio-item'
});
let portfolioFilters = select('#portfolio-flters li', true);
on('click', '#portfolio-flters li', function(e) {
e.preventDefault();
portfolioFilters.forEach(function(el) {
el.classList.remove('filter-active');
});
this.classList.add('filter-active');
portfolioIsotope.arrange({
filter: this.getAttribute('data-filter')
});
portfolioIsotope.on('arrangeComplete', function() {
AOS.refresh()
});
}, true);
}
});
页面现在看起来像这样:
但我想点击第一个
- 我尝试在第一个portfolioFilters元素中添加一个
click()
方法来模拟页面加载时第一个li元素上的click事件,但它没有改变任何东西:
window.addEventListener('load', () => {
let portfolioContainer = select('.portfolio-container');
if (portfolioContainer) {
let portfolioIsotope = new Isotope(portfolioContainer, {
itemSelector: '.portfolio-item'
});
let portfolioFilters = select('#portfolio-flters li', true);
// Click on the first li element
portfolioFilters[0].click();
on('click', '#portfolio-flters li', function(e) {
e.preventDefault();
portfolioFilters.forEach(function(el) {
el.classList.remove('filter-active');
});
this.classList.add('filter-active');
portfolioIsotope.arrange({
filter: this.getAttribute('data-filter')
});
portfolioIsotope.on('arrangeComplete', function() {
AOS.refresh()
});
}, true);
}
});
预期输出为:
请问我该怎么做?
1条答案
按热度按时间wljmcqd81#
在附加
click
侦听器之前单击元素。如果像这样重新排序代码,这应该可以工作: