2014-10-31 43 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