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

jQuery: Changing the text of a button depending on the visibility state of a table

本文关键字:按钮 文本 状态 可见性 jQuery      更新时间:2023-09-26

当表可见或不可见时,我试图使用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>

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.
        }
    });   
  });
});

你可以在这个页面或视频中了解延期和承诺背后的逻辑。

用于检查可见性:

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