2014-09-22 71 views
0
<div id="sample"> 
    <h3>headline 1</h3> 
    <h3>headline 2</h3> 
    <h3>headline 3</h3> 
</div> 

現在如何確定點擊h3子元素並用jquery處理它?jquery獲取當前的小孩數

var id = $("h3").index(); 

這不是嗎?

+2

可能重複[jQuery的:獲取元素的指數相對子到父(HTTP://計算器。 com/questions/4996002/jquery-get-index-of-element-as-child-relative-to-parent) – 2014-09-22 10:25:40

回答

1

內單擊處理程序中,你必須參考$(this)指向被點擊的元素。嘗試像

$("h3").on("click",function(){ 
 

 

 
    alert($(this).index()); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="sample"> 
 
    <h3>headline 1</h3> 
 
    <h3>headline 2</h3> 
 
    <h3>headline 3</h3> 
 
</div>

1

你需要編寫click事件上的H3元素:

$("h3").click(function() { 
    var index= $(this).index(); 
    alert(index); 
}); 

Working Demo

+0

無論什麼孩子我都只返回0點擊 – 2014-09-22 10:35:53

+0

@ DerAdmin81:在這裏可以正常工作http://jsfiddle.net/6rm371mo/ – 2014-09-22 10:41:27

1

this指數函數

$("h3").click(function(){ 
var id = $("h3").index(this); 
}) 
1

嘗試的

$("h3").click(function(event){ 
    alert($(this).index() + 1); 
}); 

DEMO