JavaScript and Jquery: Find the index of the clicked element
P粉022140576
P粉022140576 2023-08-25 14:55:21
0
1
530
<p>I'm building a slideshow and I'm having difficulty with the following question - How do I find the position (index) in an array when a label is clicked? The following code section obtains all a tags </p> <pre class="brush:php;toolbar:false;">this.thumbs = this.nav.find('a');</pre> <p>Where to start? One more problem - when the label is clicked, I need to switch the class of the div inside the label (the div label needs to get class promo_tumb_current, and the div with that label needs to lose it). </p> <p>HTML code: </p> <pre class="brush:php;toolbar:false;"><div class="promo_tumbs col_12"> <div data-dir="prev" class="prev"></div> <div data-dir="next" class="next"></div> <div class="promo_tumbs_centar"> <a href="#first"><div class="promo_tumb promo_tumb_current"></div></a> <a href="#second"><div class="promo_tumb"></div></a> <a href="#thrid"><div class="promo_tumb"></div></a> <a href="#fourh"><div class="promo_tumb"></div></a> <a href="#fifth"><div class="promo_tumb"></div></a> <a href="#fifth"><div class="promo_tumb"></div></a> <a href="#fifth"><div class="promo_tumb"></div></a> </div> </div></pre> <p>JS代码:</p> <pre class="brush:php;toolbar:false;"><script> function Slider(container, nav){ this.container = container; this.nav = nav; this.li = this.container.find('li'); this.li_width = this.li.first().width(); this.li_len = this.li.length; this.thumbs = this.nav.find('a'); this.current = 0; } Slider.prototype.transition = function (coords){ this.container.stop().animate({ 'margin-left' : coords || -(this.current * this.li_width) }) } Slider.prototype.set_current = function(dir){ var pos = this.current; if (dir === 'next') {pos } else if (dir === 'prev') {pos--} this.current = (pos < 0) ? this.li_len - 1 : pos % this.li_len; return pos; } var slider = new Slider($('div.promo_inner ul'), $('div.promo_tumbs')); slider.nav.find('div').on('click', function(){ if ($(this).attr("data-dir") === undefined ) { var index = slider.thumbs.index(); console.log(index) } else { slider.set_current($(this).data('dir')); } slider.transition(); })</pre> <p></p>
P粉022140576
P粉022140576

reply all(1)
P粉426780515

I think what you need is

http://api.jquery.com/index/

For example, in your event handler (where this is the clicked a tag):

var index = thumbs.index($(this))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!