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

2 回答 2

2

传入event你的函数,然后使用

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

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

于 2013-11-05T02:50:44.773 回答
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>
于 2013-11-05T03:17:57.607 回答