首頁  >  問答  >  主體

JavaScript和Jquery:尋找被點擊元素的索引

<p>我正在建立一個投影片,我在以下問題上遇到了困難 - 當點擊標籤時,如何在陣列中找到位置(索引)?下面的程式碼部分取得了所有的a標籤</p> <pre class="brush:php;toolbar:false;">this.thumbs = this.nav.find('a');</pre> <p>從那裡開始呢? 還有一個問題 - 當點擊標籤時,我需要切換標籤內部div的類別(div標籤需要取得class promo_tumb_current,而具有該標籤的div需要失去它)。 </p> <p>HTML代碼:</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></前> <p>JS代碼:</p> <pre class="brush:php;toolbar:false;"><腳本> 函數滑桿(容器,導航){ this.container = 容器; this.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.當前 = 0; } Slider.prototype.transition = 函數(座標){ this.container.stop().animate({ 'margin-left' : 座標 || -(this.current * this.li_width) }) } Slider.prototype.set_current = 函數(dir){ var pos = this.current; if (dir === '下一個') {pos } else if (dir === '上一個') {pos--} this.current = (pos < 0) ? this.li_len - 1 : pos % this.li_len; 返回位置; } var slider = new Slider($('div.promo_inner ul'), $('div.promo_tumbs')); slider.nav.find('div').on('點選', function(){ if ($(this).attr("data-dir") === 未定義 ) { var index = slider.thumbs.index(); 控制台.log(索引) } 別的 { slider.set_current($(this).data('dir')); } 滑桿.transition(); })</pre> <p></p>
P粉022140576P粉022140576421 天前499

全部回覆(1)我來回復

  • P粉426780515

    P粉4267805152023-08-26 09:37:08

    我認為你需要的是

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

    #

    例如,在你的事件處理程序中(其中this是被點擊的a標籤):

    var index = thumbs.index($(this))

    回覆
    0
  • 取消回覆