使用 JQuery 动态隐藏/显示 <td>


Dynamically hiding/showing a <td> using JQuery

使用 PHP,我返回了一个表,其中每行包含 3 列。第三列有一个信息图标,除非将鼠标悬停在上面,否则该图标是隐藏的。下面是生成此表的 PHP 代码片段:

$contoutput = $contoutput . '<tr><td>' . $xleft[$i] . '</td><td>' . $xright[$i] . '</td><td class="hiddensourceicon" onMouseOver="showicon(this);">' . findsource($xsource[$i]) . '</td></tr>';

hiddensourceicon的CSS很简单:

.hiddensourceicon { display: none; }

这样,所述图标在加载时不会显示。我正在使用 JQuery 删除这个类,从而在悬停时"取消隐藏"图标:

function showicon(row2show){ $(row2show).removeClass("hiddensourceicon"); }

但出于某种原因,JQuery 函数拒绝触发。我做错了什么?

当您将某些内容设置为显示 none 并尝试将鼠标悬停在不存在的内容上时,麻烦就出现了,您可以解决此问题的一种方法是使用不透明度而不是显示。如果你想继续使用显示器,你必须考虑到屏幕上必须有一些东西才能悬停。这是使用不透明度的快速解决方案。

JSFiddle: https://jsfiddle.net/kriscoulson/kg6380z8/1/

你也应该远离使用内联JavaScript。例如 mouseover="function(args);"

var $hiddenicon = $('.hiddenicon');
$hiddenicon.on('mouseover mouseout', function() {
  var opacity = $(this).css('opacity') == 1 ? 0 : 1;
  $(this).css({
    opacity: opacity
  });
});
table,
th,
td {
  border: 1px solid black;
}
.hiddenicon {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="hiddenicon">Icon</td>
    <td>Things in here</td>
    <td>Other things in here</td>
  </tr>
  <tr>
    <td class="hiddenicon">Icon</td>
    <td>Things in here</td>
    <td>Other things in here</td>
  </tr>
  <tr>
    <td class="hiddenicon">Icon</td>
    <td>Things in here</td>
    <td>Other things in here</td>
  </tr>
</table>

隐藏后再次显示它,您需要使display:block否则它不会显示,因为您使用的是jquery,因此您可以使用.hide()和.show()方法ref-http://www.w3schools.com/jquery/jquery_hide_show.asp

试试这个:

<?php
$contoutput = $contoutput . '<table cellspacing="5"><tr><td>' . "11" . '</td><td>' . "2222" . '</td><td id="xyz"  onMouseOver="showicon(this.id);"><span class="hiddensourceicon" >' . "hiiiii" . '</span></td></tr></table>';
echo $contoutput;
?>
<style>
.hiddensourceicon { display: none; }
</style>
<script>
function showicon(row2show){
var abc = "#"+row2show+" span";
$(abc).removeClass("hiddensourceicon"); }
</script>
您在

当前问题中会遇到一个问题:hiddensourceicon设置为display:none,因此没有什么可悬停的。如果将其设置为 opacity:0 ,它仍将在那里悬停。另外,opacity可以动画化 - 可能需要也可能不需要。

下面是一种方法,也许其他人会有更有效的方法,这里有一个小提琴:

$contoutput = $contoutput . '<tr><td>' . $xleft[$i] . '</td><td>' . $xright[$i] . '</td><td class="hiddensourceicon">' . findsource($xsource[$i]) . '</td></tr>';

.CSS:

.hiddensourceicon { 
  opacity:0;
}
.show {
  opacity:1;
}

j查询:

$( ".hiddensourceicon" ).hover(function() {
  $(this).toggleClass('show');
});