Home > Article > Web Front-end > jquery gets the current element index value usage example_jquery
The example in this article describes the use of jquery to obtain the current element index value. Share it with everyone for your reference. The details are as follows:
When doing the image rotation effect on the promotion page today, the left side of the page number below needs to display the description information of the image. The effect is as follows:
Things:
When the page part is in the current state, the "active" style will be added.
By obtaining the index value of li class="active", the corresponding image description information is found and displayed.
Solution:
This effect can be easily achieved through jquery’s index().
The code is as follows:
HTML:
<div id="carousel"> <div id="carouselimg"> <div id="imgcontainer"> <a href="#" mce_href="#"><img src="" /></a> <a href="#" mce_href="#"><img src="" /></a> <a href="#" mce_href="#"><img src="" /></a> <a href="#" mce_href="#"><img src="" /></a> <a href="#" mce_href="#"><img src="" /></a> </div> </div> <div id="carouseltitle"> <div class="carouseltext"> <span> </span> <span> </span> <span> </span> <span> </span> <span> </span> </div> <ul> <li><span>1</span></li> <li><span>2</span></li> <li><span>3</span></li> <li><span>4</span></li> <li><span>5</span></li> </ul> </div> </div>
JavaScript:
<SCRIPT src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" mce_src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></SCRIPT> <SCRIPT type=text/javascript> var carousedata = [ {index:0,link:"http://www.dangdang.com",imgsrc:"1.jpg",text:"数千款名品手机6折起"}, {index:1,link:"http://www.baidu.com",imgsrc:"2.jpg",text:"测试文本2"}, {index:2,link:"http://www.google.com",imgsrc:"3.jpg",text:"测试文本3"}, {index:3,link:"http://www.soso.com",imgsrc:"xf.jpg",text:"测试文本4"}, {index:4,link:"http://www.jb51.net",imgsrc:"py.jpg",text:"测试文本5"} ]; $(document).ready(function(){ $("#imgcontainer a").each(function(i){ $(this).attr("href",carousedata[i].link); $(this).children("img").attr("src",carousedata[i].imgsrc); }); $(".carouseltext span").each(function(i){ $(this).text(carousedata[i].text); }) setInterval(function(){ var li_index = $("#carouseltitle ul li").index($("#carouseltitle ul li.active")[0]); $(".carouseltext span").hide(); $(".carouseltext span").eq(li_index).show(); },10); }); </script>
Here, I use setinterval and search every 10ms.
There are areas where this code can be optimized.
I hope this article will be helpful to everyone’s jQuery programming.