jQuery不适用于新项目

时间:2015-06-30 21:55:24

标签: jquery dynamic hover

您好我想在悬停时隐藏/显示表格的行。问题是查询不能处理新动态添加的元素..

<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

4 个答案:

答案 0 :(得分:2)

使用&#39; live&#39;选择,使用.on()

所以这样:

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

答案 1 :(得分:2)

尝试事件委派:

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

答案 2 :(得分:2)

你应该使用这样的东西:

$(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/

答案 3 :(得分:1)

你可能想考虑使用CSS3过渡来做这样的事情。只需将其添加到您的CSS:

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

CSS可能更快。有关优缺点的概述,请参阅Myth Busting: CSS Animations vs. JavaScript