2011-10-21 40 views
1

我有以下的DOM結構,基於h4的點擊我需要獲取相應的類小部件的id並向服務器發送一個post請求。我對jQuery有點新,因此很掙扎。任何人都可以請幫忙?瞭解哪個孩子被點擊了jquery中的標籤

<section id="home-sidebar" class="sidebar"> 
    <div class="menu"> 

    <div class="widget" id="4"> 
     <div class="title"> 
     <h4>First Text</h4> 
     <p>Do some stuff</p> 
     </div> 
    </div> 
    .................................. 
............... 

    <div class="widget" id = "56"> 
     <div class="title"> 
     <h4>N-th Text</h4> 
     <p>Do some stuff</p> 
     </div> 
    </div> 
    </div> 
</section> 

我怎麼知道哪個H4標籤被點擊jQuery的?我如何獲得小部件的相應「ID」號碼? (注IDS是不連續的,他們可以隨意爲好)

+0

數值不是用於ID屬性有效W3值。 ID和名稱標記必須以字母([A-Za-z])開頭,後面可以跟隨任意數量的字母,數字([0-9]),連字符(「 - 」),下劃線(「_」) ,冒號(「:」)和句點(「。」)。 – jbabey

回答

1

你可以使用.parents()找到具有您希望獲取的ID的DOM節點:

//bind a click handler to all h4 elements 
$('h4').bind('click', function() { 
    //find the id of the parent node that has the .widget class 
    //since you are trying to get the id, you do not need to use the jQuery .attr() function which performs slower than the below code 
    var id = $(this).parents('.widget')[0].id; 
    $.get('path/to/server.file?id=' + id, function (data) { 
     //this is the callback function for the server request 
     alert('Server Response: ' + data); 
    }); 
}); 

文檔爲.parents()http://api.jquery.com/parents/

0

如果你這樣做:

$('h4').click(....) 

你可以這樣來做:

$('h4').click(function(){ 
    alert($(this).attr('id')) 
}) 
0
$(document).ready(function(){ 
    $(".widget").click(function(){ 
     var id = $(this).attr("id"); //gives id 
    }); 
}); 
0
$("h4").click(function(){ 
    var a=$(this).parent().parent().attr('id'); 
    alert(a); 
})