2013-07-20 46 views
0

我使用ajax將XML加載到表中,並嘗試執行「懸停」事件以在鼠標懸停在表格行和表格行之外時更改顏色。表格行是使用AJAX動態添加的。它不工作。以下是代碼:jQuery on()函數和懸停事件

$(document).ready(function(){ 
    //$("tr").hover(function(){ 
    $("#tbl1").on("hover","tr",function(){ 
     $(this).attr('bgcolor', "yellow"); 
    }, 
    function(){ 
     $(this).attr('bgcolor', "white"); 
    });  
}); 

而下面表時提前頁面加載

<table width="200" border="5" cellspacing="5" cellpadding="5" id="tbl1"> 
    <tr> 
     <th scope="col">Index</th> 
     <th scope="col">Matriks</th> 
     <th scope="col">Name</th> 
     <th scope="col">IC</th> 
     <th scope="col">Age</th> 
     <th scope="col">Photo</th> 
    </tr> 
</table> 

感謝您的幫助

回答

0

試試這個:

$(document).ready(function() { 
    $("#tbl1").on("mouseenter", "tr", function() { 
     $(this).attr('bgcolor', "yellow"); 
    }).on("mouseleave", "tr", function() { 
     $(this).attr('bgcolor', "white"); 
    }); 
}); 

jsFiddle

+0

這也行得通,謝謝:D –

+0

這個更好的代碼,整齊,謝謝 –

+0

不客氣! –

0

使用此功能

$("#tbl1 tr").live("hover",function(){ 
    $(this).attr('bgcolor', "yellow"); 
}, 
function(){ 
    $(this).attr('bgcolor', "white"); 
});  
0

試試這個

$(document).ready(function(){ 
    $("#tbl1").on("mouseenter","tr",function(){ 
     $(this).attr('bgcolor', "yellow"); 
    }, 
    function(){ 
     $(this).attr('bgcolor', "white"); 
    });  
}); 

懸停是mouseenter和mouseleave事件的簡寫形式。懸停,因爲這不是一個事件。和。對( '懸停' ..不是有效的語法。 但是你可以使用$( 「#TBL1 TR」)。懸停(函數(){})直接。

0

使用.css(),而不是.attr()

$(document).ready(function() { 
    $("#tbl1 tr").hover(function() { 
     $(this).css("background-color", "yellow"); 
    }, 

    function() { 
     $(this).css("background-color", "white"); 
    }); 
}); 

入住這JSFiddle

+0

真的需要進行動態連續的()函數,否則不能正常工作。謝謝 –

0

懸停在TR突出TR

工作演示http://jsfiddle.net/4SjZ7/1

$(document).ready(function() { 
    $("#tbl1 tr").hover(function() { 
     $(this).attr('bgcolor', "yellow"); 
    }, 
    function() { 
     $(this).attr('bgcolor', "white"); 
    }); 
}); 

,如果你想表和突出懸停在TR這個代碼

工作演示http://jsfiddle.net/4SjZ7/3/

JS

$(document).ready(function() { 
    $("#tbl1").hover(function() { 
     $('#tbl1 tr').attr('bgcolor', "yellow"); 
    }, 
    function() { 
     $('#tbl1 tr').attr('bgcolor', "white"); 
    }); 
}); 
0

這似乎爲我工作: http://jsfiddle.net/Sde8J/2

$(document).ready(function(){ 

    $("#tbl1 tr").hover(
    function() { 
    $(this).css("background-color", "yellow"); 
    }, 
    function() { 
    $(this).css("background-color", "white"); 
    }); 
}); 
+0

它工作,如果行是硬編碼,問題是隻有當該行動態使用AJAX添加 –