2013-11-05 121 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>