简体   繁体   English

我如何通过计数jquery中的元素来通过循环生成代码

[英]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 我想动态计数元素并根据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. 代码详细信息:.accordion .toggle是元素,它是动态生成的,在for循环代码之间,当我单击该元素时,它的工作原理将显示img src="img1.jpg" ,与第二个元素可用时我希望的效果相同, img2.jpg可用。

the issue I am facing is if elements are available 6 then code generate 6th for all elements. 我面临的问题是,如果元素可用6,则代码为所有元素生成第六个。 but I want to be separated for all. 但我要为所有人分开。

This is because $(".accordian-left-image img").attr('src','https://img'+i+'.jpg'); 这是因为$(".accordian-left-image img").attr('src','https://img'+i+'.jpg'); selects every accordian-left-image class. 选择每个accordian-left-image类。 To fix this, use the .eq() selector: 要解决此问题,请使用.eq()选择器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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