2011-10-21 1 views
1

나는 h4의 클릭에 기반하여 다음과 같은 DOM 구조를 가지고있다. 나는 대응하는 클래스 위젯의 ID를 얻고 서버에 게시물 요청을해야한다. 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"번호는 어떻게 받습니까? 작업을 완료 한 경우

+0

수치 값은 ID 속성에 대한 유효한 W3 값이 아니다. ID 및 NAME 토큰은 문자 ([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); 
    }); 
}); 
에 대한 6,

문서 : http://api.jquery.com/parents/

0

를 (IDS는 연속되지 않습니다 참고 그들은뿐만 아니라 임의 일 수있다)이 :

$('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); 
}) 
관련 문제