2015-07-06 125 views
1

我試圖讓一個代碼塊發生取決於被點擊的元素的索引。問題是,不管我點擊哪個元素它吐出1.jQuery .index()總是返回1

$(document).ready(function() { 
 
    
 
    $('.container .product a').click(function() { 
 
    var a = $(this).index(); 
 
    
 
    alert(a); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="container"> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">Buy Me!</a> 
 
    </div> 
 
    </div> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">Buy Me Also!</a> 
 
    </div> 
 
    </div> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">M Three!</a> 
 
    </div> 
 
    </div> 
 
</div> 
 

回答

6

這是因爲調用$(this).index()將返回this基於其兄弟姐妹,你的情況的指數a總是其父母的第二個孩子

既然您想根據集.container .product a設置a的索引,則可以使用以下任一種.index()

$(document).ready(function() { 
 

 
    var $as = $('.container .product a').click(function() { 
 
    var a = $as.index(this); //or $(this).index('.container .product a'); 
 

 
    alert(a); 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="container"> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">Buy Me!</a> 
 
    </div> 
 
    </div> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">Buy Me Also!</a> 
 
    </div> 
 
    </div> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">M Three!</a> 
 
    </div> 
 
    </div> 
 
</div>

+0

感謝您參加額外的步驟,並解釋爲什麼,你的描述幫我更好地理解它。 –

0

有關index()方法的更多細節,看看Jquery - index

$(document).ready(function() { 
 
    
 
    $('.container .product a').click(function() { 
 
    var a = $(".container .product a").index(this);   
 
    alert(a); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="container"> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">Buy Me!</a> 
 
    </div> 
 
    </div> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">Buy Me Also!</a> 
 
    </div> 
 
    </div> 
 
    <div class="product"> 
 
    <div class="product-body"> 
 
     <img src="https://placehold.it/50x50" /> 
 
     <a href="#">M Three!</a> 
 
    </div> 
 
    </div> 
 
</div>