简体   繁体   中英

How can i generate code through loop by counting elements in jquery

I want to count element dynamically and generate code as per elements are available in HTML

here is code:

$(window).load(function(){                                                

var count= $(".accordion .toggle").length;
var i;

for(i=0; i<=count; i++){
    $(".accordion li a").eq(i).click(function(){
    alert(i+" image");
    $(".accordian-left-image img").attr('src','https://img'+i+'.jpg');
    });
}; });

Code Details: .accordion .toggle is elements and it's generated dynamically, between for loop code its works when I click on the element it will show img src="img1.jpg" the same thing I want that works when 2nd elements are available and img2.jpg is available.

the issue I am facing is if elements are available 6 then code generate 6th for all elements. but I want to be separated for all.

This is because $(".accordian-left-image img").attr('src','https://img'+i+'.jpg'); selects every accordian-left-image class. To fix this, use the .eq() selector:

$(".accordian-left-image img").eq(i).attr('src','https://img'+i+'.jpg');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM