jQuery 不适用于新项目

jQuery not working for new items

您好,我想 hide/show 悬停 table 的行。问题是查询不适用于新动态添加的元素..

<button id="myButton">Add New Row</button>
<br/>
<br/>

<br/>
<table id="myTable">
    <tr>
        <td>This is a static row.</td>
    </tr>
</table>



$("#myButton").click(function () {

   var newRow = '<tr><td>This is a dynamically added row.</td></tr>'; 
    $('#myTable').append(newRow);
});



 $('#myTable tr').hover(

       function() {
       $(this).animate({opacity: 0}, 1);

     },
     function() {

         $(this).animate({opacity: 1}, 1);
     }

    );

这里有一个例子:link

要使用 'live' 选择,请使用 .on()

像这样:

$('body').on({
    mouseenter: function() {
        $( this ).animate({opacity: 0}, 1);
    }, mouseleave: function() {
        $( this ).animate({opacity: 1}, 1);
    }
},'#myTable tr');

尝试事件委托:

 $(document).on("mouseenter", "#myTable tr", function(){
         $(this).animate({opacity: 0}, 1);
 });

 $(document).on("mouseleave", "#myTable tr", function(){
         $(this).animate({opacity: 1}, 1);
 });

Understanding Event Delegation

你应该使用这样的东西:

$(staticAncestors).on(eventName, dynamicChild, function() {});

以下是它在您的代码中的应用方式:

$("#myButton").click(function () {

   var newRow = '<tr><td>This is a dynamically added row.</td></tr>'; 
    $('#myTable').append(newRow);
});

$('#myTable').on( "mouseover", "tr", function () {
    $(this).animate({opacity: 0}, 1);
});

$('#myTable').on( "mouseout", "tr", function () {
    $(this).animate({opacity: 1}, 1);
});

JSFiddle:http://jsfiddle.net/Lfuugkw2/3/

您可能需要考虑使用 CSS3 转换来实现类似的效果。只需将此添加到您的 CSS:

#myTable tr:hover {
    opacity: 0;
    transition: opacity 0.2s ease;
}

CSS 可能更快。有关 pros/cons 的概述,请参阅 Myth Busting: CSS Animations vs. JavaScript