2013-03-26 96 views
0

我正在嘗試創建一個'打印'按鈕來打開一個新窗口並在其中顯示一個PHP變量。Jquery - 用當前頁面的內容打開一個新窗口

下面的代碼通過PHP腳本循環多次,但是我看不到要打開窗口時顯示的正確數字(打印鏈接中顯示的數字是正確的 - 但是當新窗口打開時是不正確的)。

<script type='text/javascript'> 
jQuery(function($) { 
$('a.new-window').click(function(){ 

var recipe = window.open('','PrintWindow','width=600,height=600'); 
var html = '<html><head><title>Print Your Ticket</title></head><body><div id="myprintticket">' + $('<div />').append($('#ticket').clone()).html() + '</div></body></html>'; 
recipe.document.open(); 
recipe.document.write(html); 
recipe.document.close(); 

return false; 

}); 
}); 
</script> 

<a href="" class="new-window">Print <?php echo $EM_Booking->get_spaces() ?></a> 

<div style="display:none;"> 
<div id="ticket"><?php echo $EM_Booking->get_spaces() ?> 
</div> 

</div> 
+0

如果這是多次循環 - 你有許多#ticket元素。 html元素的ID必須是唯一的。 – tborychowski 2013-03-26 12:48:55

回答

1

爲什麼不嘗試這樣的事:

<a href="#" class="new-window">Print <?php echo $EM_Booking->get_spaces() ?> 
    <div class="ticket" style="display:none"> 
     <?php echo $EM_Booking->get_spaces() ?> 
    </div> 
</a> 


<script> 
jQuery(function ($) { 

    $('a.new-window').click(function() { 
     var btn = $(this), 
      ticket = btn.find('.ticket').html(),    
      recipe = window.open('','PrintWindow','width=600,height=600'), 
      html = '<html><head><title>Print Your Ticket</title></head><body><div id="myprintticket">' + ticket + '</div></body></html>'; 
     recipe.document.open(); 
     recipe.document.write(html); 
     recipe.document.close(); 
     return false; 
    }); 

}); 
</script> 

但更好的解決辦法是讓一個按鈕一個唯一的ID,和的onclick從服務器通過打開現有(PHP生成)頁該ID,例如/getBooking.php?id=123並且該頁面將輸出任何所需的內容。

+0

嗨,那完美!非常感謝你提供這樣一個快速解決方案:) – Meakin 2013-03-26 13:03:13

+0

只是另一個快速問題 - 當我把任何HTML(即123)放入其中一個PHP回聲中時,它會打破腳本並顯示「未定義」,我將如何去清理內容避免這種情況? – Meakin 2013-03-26 13:41:27

+0

@Meakin我不確定我是否理解這個問題。你能否請一些代碼,比如用打破腳本的html?(或者可能會開始一個新問題,因爲這個問題似乎與這個問題無關當前一個) – tborychowski 2013-03-26 14:00:33

相關問題