JavaScript/jQuery2010. 11. 15. 22:05

예제

 


위의 이미지는 예제를 위한 것이다.

일단 위와 같은 레이아웃이 있을 경우 각 엘리먼트를 클릭한 경우 해당 값 또는 인덱스를 알아 오고자 하는 경우가 있다. 이런 경우 jquery의 selector이용하면 쉽게 해당 값을 확인 할 수 있다.

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
          $(document).ready(function(){
               $("ul#ulBox li").click(function(){
                    alert($('li').index(this));  //return index, index start from zero(0)
               });
               $("table#tableBox td").click(function(){
                    alert( $('td').index(this) +" : "+$(this).attr('tag')); // index +" : "+ tag value
                    //$(this).attr('tag') -> attr대신 css등을 사용 할 수있다.
               });
          });
</script>

<ul id="ulBox">
     <li>aaa</li>
     <li>bbb</li>
     <li>ccc</li>
     <li>ddd</li>
</ul>

<table border="1" cellspacing="0" cellpadding="0" id="tableBox">
     <tr>
          <td style="width:100px" tag="val0">aaaa</td>
     </tr>
     <tr>
          <td tag="val1">bbbb</td>
     </tr>
     <tr>
          <td tag="val2">cccc</td>
     </tr>
     <tr>
          <td tag="val3">dddd</td>
     </tr>
</table>
Posted by Jake Kim