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

I have several <li> and I need trigger a click event over all them when the page is loaded. I hav

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();
    }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745375219a4624967.html

相关推荐

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

    I have several <li> and I need trigger a click event over all them when the page is loaded. I hav

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信