开发者

jQuery: Replace and remove HTML snippet on hover

开发者 https://www.devze.com 2023-03-29 19:07 出处:网络
I\'m extremely new to jQuery.I\'m trying to have it so that the text in a td is replaced with a HTML snippet when the tr is hovered over and then reverted back to the original td content afterward.

I'm extremely new to jQuery. I'm trying to have it so that the text in a td is replaced with a HTML snippet when the tr is hovered over and then reverted back to the original td content afterward.

Thanks in advan开发者_运维百科ce!


Something like this will do it:

var originalContent = $('.myTR td').html();
$('.myTR').hover(function() {
     $('.myTR td').html('<strong>New HTML</strong>');   
}, function() {
     $('.myTR td').html(originalContent); 
});

Assuming your HTML looks like this:

<table>
    <tr class="myTR">
        <td>Text td</td>
    </tr>
</table>

You can test it here


IF your HTML looks something like this:

<table>
<tr id="hoverRow">
    <td id="contentCell" style="background-color: blue;">Content to Replace</td>
    <td>Other Content</td>
</tr>
</table>

You can do something like this:

<style type="text/javascript">
    var savedHtml = $('#contentCell').html();
    $('#hoverRow').hover(
        function () {
          $('#contentCell').html('New content');
          $('#contentCell').attr('background-color', 'red');
        }, 
        function () {
          $('#contentCell').html(savedHtml);
          $('#contentCell').attr('background-color', 'blue');
        }
    );
</script>


I found a way to do this, but you'll need something like a hidden field, or some other variable to stash the original content.

Something like this html:

<table id="table">
    <tr id="tr">
        <td>Some Text</td>
    </tr>
</table>

<input id="hidden" type="hidden" />

And this jQuery:

$('#tr').hover(
    function(){
       $('#hidden').val($('#tr > td').text());
       $('#tr > td').text('Some Other Text');
    }, 
    function(){
        $('#tr > td').text($('#hidden').val());    
    }
);

See it work here: http://jsfiddle.net/davecoulter/HgAyv/

0

精彩评论

暂无评论...
验证码 换一张
取 消