如何检索选择了哪个子项

时间:2013-11-05 02:47:02

标签: jquery html

我需要告诉我点击了哪个孩子,这样我才能更改该特定行的背景颜色。

<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>

2 个答案:

答案 0 :(得分:2)

event传递给您的函数,然后使用

$(event.target).addClass("yourClass");

使用ul进行演示:http://jsfiddle.net/WS7VK/

答案 1 :(得分: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>