事件委托的应用

对于表格,有时我们的行是js创建的添加到table中的,那么我写的公共js就不管用了,如下:

 $(".tr:odd").each(function () {
        $(this).hover(function () {
            $(this).css("background-color", "#D9DEE4");
        }, function () {
            $(this).css("background-color", "#f5f5f5");
       });
   });
    $(".tr:even").each(function () {
        $(this).hover(function () {
            $(this).css("background-color", "#D9DEE4");
        }, function () {
            $(this).css("background-color", "#fff");
       });
    });

都是在js里的写的,无论我把js样式放哪个位置都不能更改样式

如何解决呢?

这个时候就是委托事件了。

<table></table>并不是在js中中创建的,本就在html里.

 1 $('.list_table').on('mouseover', '.tr:odd', function () {
 2         $(this).css("background-color", "#D9DEE4");
 3     })
 4     $('.list_table').on('mouseleave', '.tr:odd', function () {
 5         $(this).css("background-color", "#f5f5f5");
 6     })
 7     $('.list_table').on('mouseover', '.tr:even', function () {
 8         $(this).css("background-color", "#D9DEE4");
 9     })
10     $('.list_table').on('mouseleave', '.tr:even', function () {
11         $(this).css("background-color", "#fff");
12     })

这样就解决问题了。

posted @ 2017-03-22 16:57  niu2016  阅读(88)  评论(0编辑  收藏  举报