2013-03-24 4 views
0

jQuery를 사용하고 있습니다. -----Jquery - 함수를 실행하기 위해 클릭 한 요소에 어떻게 액세스합니까?

<table> 
<tr> 
<td class="cell" id="cell1" ></td> 
<td class="cell" id="cell2"></td> 
<td class="cell" id="cell3" ></td> 

</tr> 

<tr> 
<td class="cell" id="cell4"></td> 
<td class="cell" id="cell5"></td> 
<td class="cell" id="cell6"></td> 

</tr> 

</table> 

--- JS ----

$(".cell").click(function() { 

do_something(); 

} 

function do_something(){ 

// I want to print the id of the cell that was clicked here . 

} 

내가 어떻게

---- HTML 액세스 - 나는 몇 가지 코드를 아래와 같이가 함수가 실행되는 원인은 무엇입니까? 위의 코드에서 예를 들어, 단순히 직접 호출하는 것이 더 간단 할 것이다 함수 do_Something() 물론

+0

, 그래서이 시도 : $ (이) .attr ('ID') – tuffkid

+2

는'this.id'는 훨씬 더 ... –

답변

3
$(".cell").click(function() { 
    do_something(this); // this is the clicked element 
}); 
function do_something(element){ 
    console.log(element.id); // open the console to see the result 
} 

내부에서 클릭 된 셀의 ID에 액세스하려면 :

$(".cell").click(do_something); 
function do_something(){ 
    console.log(this.id); // open the console to see the result 
} 

또는

그가 ID로 값을 표시하고자
$(".cell").click(function(){ 
    console.log(this.id); // open the console to see the result 
}); 
+0

감사합니다! 코드의 여러 위치에서 이렇게해야하기 때문에 함수를 안에 넣을 수 없습니다. 코드를 불필요하게 반복합니다. –

관련 문제