2013-07-30 3 views
0
<div class="top"> 
    <div class="hp_class"> 
     This is div1. 
    </div> 
    <div> 
     <form id="newsletter" name="myForm" method="post">  
      <div class="hp_rt"> 
       <div class="subscribe subs_failure">Subscribe now</div> 
      </div> 
     </form> 
    </div> 
    <div class="hp_class"> 
     This is div3. 
    </div> 
</div> 

мне нужен индекс div тега,получить индекс DIV с помощью Jquery

Например, если я нажму на Subscribe now, мне нужно индекс его как 2

код я попытался это

$('.hp_rt>.subscribe').click(function(){ 
    var div_count=$(this).parent('.hp_promo_rt').parents('div').index($(this).parent('.hp_rt').parents('div')); 
    alert(div_count); 
}); 
+0

См. http://api.jquery.com/index/ – Stefan

+0

как 2? я не думаю, что индекс Div будет 2 ... – Kasma

+0

u нужно, сколько divs? –

ответ

0

Вы можете сделать это так:

$('.hp_rt>.subscribe').click(function() { 
    var $div = $(this).parents('.top > div'); // This is the Div you want the index of! 
    var $prevs = $div.prevAll('div'); // This are all the Divs before the Div! 
    var number = $prevs.size() + 1; // There is one div before the div in question, so this gives 2 in this case. 
}); 

В качестве альтернативы можно использовать индекс():

$('.hp_rt>.subscribe').click(function() { 
    var $div = $(this).parents('.top > div'); // This is the Div you want the index of! 
    var number = $div.index() + 1; 
}); 
+1

Спасибо yaar .... Первый из них для меня очень похож '$ (this) .closest ('form') .parent(). prevAll ('div'). size(); ' –

+1

@DebjeetDash ваше решение не является модульным вообще, что, если когда-нибудь в будущем вам нужно изменить структуру и обернуть свою форму в другом элементе, это будет сломать свой код –

1

Я хотел бы предложить:

$('.subscribe').click(function(){ 
    var i = $(this).closest('form').parent().index(); 
    console.log(i); 
}); 

JS Fiddle demo.

Хотя JavaScript основан на нулевом значении, так что это вернет (учитывая ваш HTML-код) 1, а не 2.

Ссылки:

1

Так что я понимаю, что вы хотите индекс в отношении прямых детей .top , использование этого

$('.hp_rt>.subscribe').click(function(){ 
    alert($(this).closest('.top > div').index()); 
}); 

T он даст вам индекс на основе нуля, вы можете добавить 1, чтобы получить оповещение как «2»

Смежные вопросы