最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger click event to a list of items - Stack Overflow

programmeradmin1浏览0评论

I have several <li> and I need trigger a click event over all them when the page is loaded. I have tried doing this with a loop but it's not working. Any help?

<ul>
    <li class="du">One</li>
    <li class="du">Two</li>
    <li class="du">Three</li>
</ul>
jQuery(document).ready(function() {
    var list = $('.du');
    for (i = 0; i <= list.length; i++) {
        $(list).click();
    }
});

I have several <li> and I need trigger a click event over all them when the page is loaded. I have tried doing this with a loop but it's not working. Any help?

<ul>
    <li class="du">One</li>
    <li class="du">Two</li>
    <li class="du">Three</li>
</ul>
jQuery(document).ready(function() {
    var list = $('.du');
    for (i = 0; i <= list.length; i++) {
        $(list).click();
    }
});
Share Improve this question edited Jan 4, 2016 at 11:29 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jan 4, 2016 at 11:22 AntonioAntonio 3952 gold badges4 silver badges15 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

You don't need to loop, just select all the .du elements and call click(). jQuery will raise the event on all matched elements in the set by itself:

$('.du').click();

Example fiddle

Also note that to loop over a set of elements selected with jQuery you should use the each() method, and refer to the element of the current iteration using the this keyword:

$('.du').each(function() {
    console.log(this);
});

Instead, you can simply do

$('.du').click(); // Will trigger click on all .du

In your code pick the element from list and click

jQuery(document).ready(function(){
    var list = $('.du');
    for(i=0;i<=list.length;i++){
      list.eq(i).click();
    }
});
发布评论

评论列表(0)

  1. 暂无评论