簡體   English   中英

如何確保在HREF觸發之前下載並顯示圖像?

[英]How can I ensure an image is downloaded and shown before a HREF fires?

我有這個代碼:

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的重定向執行到新頁面。 當我刪除圖像的onclick事件

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

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

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

你可以使用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;
   })        
})

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM