2012-07-06 41 views
0

我有這樣的代碼:如何確保在HREF發生火災之前下載並顯示圖像?

function Imagehover(obj,img){    
    jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");    
} 
function Imageclick(obj,img){        
    jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");   
} 
function Imageout(obj,img){                  
    jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");         
} 

<a href="<?php echo JURI::root(); ?><?php echo $langsefs->sef;?>"><img id="<?php echo $langsefs->sef;?>flag" style="height: 40px;margin-right: 10px;width: 47px;" src="<?php echo JURI::root(); ?>/templates/codecraft.gr/images/<?php echo $langsefs->sef; ?>_flag.png" onclick="Imageclick(this,'<?php echo $langsefs->sef; ?>_flag_pressed')" onmouseout="Imageout(this,'<?php echo $langsefs->sef; ?>_flag')" onmouseover="Imagehover(this,'<?php echo $langsefs->sef; ?>_flag_over')" alt="<?php echo $langsefs->sef; ?>"/></a> 

但是當過我點擊該標誌,圖像自敗,然後HREF的執行重定向到新的頁面。 當我刪除圖像

function Imageclick(obj,img){        
    //jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");  
} 

圖像不會消失的onclick事件。所以我認爲onclick事件觸發並嘗試從服務器獲取圖像,但由於href也被執行,圖像沒有機會到達用戶的瀏覽器,因爲頁面重定向已經開始。

如何確保將圖像下載到用戶的瀏覽器,然後進行重定向,同時需要刪除href屬性?

回答

2

您可以使用event.preventDefault()

如果此方法被調用時,事件的默認動作不會被觸發。

$('a').click(function(e){ 
    e.preventDefault(); 
    var href = $(this).attr('href'); 
    $("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png").promise().done(function(){ 
     window.location = href; 
    })   
}) 
+0

so e.preventDefault();做的伎倆。謝謝 – themis 2012-07-06 20:43:13

+1

和.promise()。done .. cool – themis 2012-07-06 20:58:06

+0

@themhz歡迎:) – undefined 2012-07-06 20:58:55

0

從事件處理程序返回false以防止默認行爲。如果希望頁面地址在後面更改,您可能需要在替換圖像後在每個處理程序中放置一個位置重定向。

相關問題