首页 > 解决方案 > 如何在数据表中的鼠标悬停时显示图像预览

问题描述

当鼠标悬停在数据表的数据上时,我想显示/隐藏图像<td>。单击按钮时我填充数据表。这是我的代码

<script>
if($.fn.dataTable.isDataTable( '#example' )){
    var table = $('#example').DataTable();
}
function getData(){
    $('#example tbody').html('');
    var URL_PREFIX="http://localhost:8983/solr/archiveCore/select?q=strSO_copy:";
    var URL_MIDDLE="AND PackName_copy:";
    var URL_SUFFIX="AND DocType_copy:";
    var strSO="\"" + $("#ngramBoxstrSO").val() + "\"";
    var PackName="\"" + $("#ngramBoxPackName").val() + "\"";
    var DocType="\"" + $("#ngramBoxDocType").val() +"\"";
    var URL=URL_PREFIX + strSO + URL_MIDDLE + PackName + URL_SUFFIX + DocType;
    $.ajax({
        url:URL,
        dataType:'jsonp',
        jsonp : 'json.wrf',
        type :'get',
        cache :false,
        success: function(data){
            var docs=data.response.docs;
            var html='';
            $.each(docs,function(key,value){
                html+='<tr>';
                html+='<td>'+value.id+'</td>';
                html+='<td>'+value.strSO+'</td>';
                html+='<td>'+value.PackName+'</td>';
                html+='<td>'+value.DocType+'</td>';
                html+='<td>'+value.DocName+'</td>';
                html+='<td class="text-center"><button id="'+value.FilePath+'" type="button" onclick="openDocument(this.id)" class="btn btn-sm" >OPEN</td>';
                html+='<td class="text-center"><a href="#" class="preview">Image Preview<img src="~\images\TEC.jpg" class="hide-image" style="position:absolute;z-index:100;"></a></td>';
                html+='</tr>';
            });
            $('#example').DataTable().destroy();
            $('#example tbody').html(html);
            var table=$('#example').DataTable({
                "aaSorting" : [],

            });
        },
    });


};

</script>

我正在使用这个 jquery 代码来显示/隐藏图像。

<script>
$(document).ready(function () {
    $(".preview").hover(function(){
        $(this).find('img').fadeIn();
     }, function(){
        $(this).find('img').fadeOut();
    });
});
</script>

我尝试了很多方法来做到这一点,但它对我不起作用。你有什么建议吗?

标签: jquery

解决方案


由于.preview是动态添加的,因此您必须使用on()

例子:

$("body").on("mouseover", ".preview", function() {
  $(this).find('img').fadeIn();
});

$("body").on("mouseout", ".preview", function() {
  $(this).find('img').fadeOut();
});

推荐阅读