2014-10-31 41 views
0

我试图通过使用jQuery来更改表的按钮的文本。问题是,jQuery .is(":visible")似乎没有做到这一点。我究竟做错了什么?我认为.is(":visible")是需要检查一个元素是否可见。jQuery:根据表的可见性状态更改按钮的文本

$(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>

回答

3

jQuery的.fadeToggle()方法将需要一些时间来执行和并行[寻找在jQuery的承诺]执行。在你的代码中,当调用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是解释他们推迟和承诺来检查。

+0

谢谢!这正是问题。感谢您发现了移动的问题;-) – PhoneixS 2014-10-31 10:41:02

0

使用检查可见:

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

你知道为什么我的代码不好吗?我想使用JQuery(如果可以使用的话)。 – PhoneixS 2014-10-31 10:31:22

+0

我放的代码是jQuery。这是因为.hide()添加了“display:none;” css指令到你的表,所以使用我的代码来检查,它会没事的。 – 2014-10-31 10:34:18

+1

这个问题得到了答案!对我来说这似乎很不错!检查上面的答案! – 2014-10-31 10:43:53