jquery 如何< li>在我来到页面时自动点击第一个?

toiithl6  于 2023-04-05  发布在  jQuery
关注(0)|答案(1)|浏览(222)

我有一个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);
    }
  });

预期输出为:

请问我该怎么做?

wljmcqd8

wljmcqd81#

在附加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);

let portfolioFilters = select('#portfolio-flters li', true);
// Click on the first li element
portfolioFilters[0].click();

相关问题