2013-11-05 86 views
0

我需要告訴哪個孩子被點擊了,所以我可以改變該特定線的背景顏色。如何檢索選擇哪個孩子

<script> 
     var counter = 0; 
     $(document).ready(function(){ 
      $(".eastern > ul").click(function(){ 
       counter++; 
       $(".northern > ul").append("<li>Champlain " + counter.toString() + "</li>"); 
      }); 
      $(".northern > ul").click(function(){ 
       $(".northern > ul").children(':nth-child(n)').css("background-color","blue"); 
      }); 
     }); 
    </script> 
+0

您可以創建一個小提琴? – karthikr

+0

'counter.toString()'是不必要的。 Javascript沒有變量類型,當你使用'+ integer +'字符串'時,它會自動將它與字符串合併 – Deryck

回答

0

this值將導致該事件處理程序中的事件的對象(見評論添加到您的腳本)。

<script> 
    var counter = 0; 
    $(document).ready(function(){ 
     $(".eastern > ul").click(function(){ 
      // the this pointer here contains the object that was clicked on 
      counter++; 
      $(".northern > ul").append("<li>Champlain " + counter.toString() + "</li>"); 
     }); 
     $(".northern > ul").click(function(){ 
      // the this pointer here contains the object that was clicked on 
      $(".northern > ul").children(':nth-child(n)').css("background-color","blue"); 
     }); 
    }); 
</script> 

所以,如果你想改變的只有顏色點擊子對象,你能做到這一點是這樣的:

<script> 
    var counter = 0; 
    $(document).ready(function(){ 
     $(".eastern > ul").click(function(){ 
      // the this pointer here contains the object that was clicked on 
      counter++; 
      $(".northern > ul").append("<li>Champlain " + counter.toString() + "</li>"); 
     }); 
     $(".northern > ul").click(function(){ 
      // set color of children of the clicked-on object 
      $(this).children().css("background-color","blue"); 
     }); 
    }); 
</script>