jQuery:根据表的可见性状态更改按钮的文本

时间:2014-10-31 10:00:51

标签: javascript jquery

我正在尝试使用 jQuery 在表格可见时更改按钮的文本。问题是jQuery .is(":visible")似乎没有这样做。我究竟做错了什么?我认为.is(":visible")是检查元素是否可见所需的内容。

$(function() {
    $( "#tabla" ).hide(); // We start hiding it.
    $("#boton").click(function() {

    var tabla = $("#tabla");

    tabla.fadeToggle();// Change the table visibility

    // An tell us if it is visible or not
    if (tabla.is(":visible")) {
        alert("It's visible"); // This is always called.
      // TODO Change button text.
    } else {
        alert("It isn't visible"); // This is never called.
      // TODO Change button text.
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p><button id="boton">Show</button></p>
<table id="tabla" >
  <thead>
    <tr><th id="cabecera">First</th><th>Second</th></tr>
  </thead>
  <tbody>
    <tr>
      <td>Foo</td><td>Boo</td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:3)

jQuery .fadeToggle()方法将花费一些时间来执行并且并行执行[在jQuery中查找promise]。在您的代码中,一旦调用fadeToggle,您就会检查表的可见性,因此它还没有时间完成。

可能你想在功能完成后检查可见光。如果要检查切换功能何时完成,则必须使用回调

$(function() {
  $( "#tabla" ).hide(); // We start hiding it.
  $("#boton").click(function() {
    var tabla = $("#tabla");
    tabla.fadeToggle( "fast", "linear" , function(){
        // This function will be called when the fade function completes
        // An tell us if it is visible or not
        if (tabla.is(":visible")) {
          alert("It's visible");
          // TODO Change button text.
        } else {
          alert("It isn't visible");
          // TODO Change button text.
        }
    });   
  });
});

您可以查看解释它们的pagevideo中延迟和承诺背后的逻辑。

答案 1 :(得分:0)

用于检查可见性:

if (tabla.css('display') != 'none') {
   alert('is visible');
} else {
   alert('is NOT visible');
}
相关问题