2013-04-30 47 views
2

我有以下jQuery,當我單擊按鈕時用於隱藏/顯示iFrame。使用jQuery添加或刪除屬性切換到隱藏/顯示項目

iFrame包含一些PHP,我只想在顯示iFrame時加載它。

$(document).ready(function() 
    { 
     $('#button').click(function() 
      { 
       $('#graphFrame').toggle().attr('src', 'graph1.php');  
      } 
     ) 
    } 
); 

這工作得很好,但它也嘗試加載PHP,當我隱藏的iFrame。

有沒有辦法告訴它當我顯示iFrame(並因此加載php)時添加'src'屬性,並且當我隱藏iFrame(因此不加載PHP)時將其刪除?

回答

1

嘗試

$('#graphFrame').toggle(function(){ 
    var $this = $(this); 
    $this.is(":visible") ? $this.attr('src', 'graph1.php') : $this.removeAttr('src') 
}); 
+1

這是偉大的乾杯,並根據需要精確地工作。 – IGGt 2013-04-30 15:56:38

1

試試這個:

$(document).ready(function() { 
    $('#button').click(function() { 
     $('#graphFrame').toggle(); 
     $('#graphFrame:visible').attr('src', 'graph1.php'); 
    }); 
}); 
1

你可以試試這個

$('#button').click(function(){ 
    var ifr = $('#graphFrame'); 
    ifr.toggle(function(){ 
     if(ifr.is(':visible')) ifr.attr('src', 'graph1.php'); 
     else ifr.attr('src', ''); 
    }); 
}); 

DEMO.

+0

謝謝,我特別喜歡這個讓圖形滑入視圖的事實。 – IGGt 2013-04-30 16:27:03

+0

不客氣:-) – 2013-04-30 16:31:47