如何确保在 HREF 触发之前下载并显示映像

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

本文关键字:下载 映像 显示 HREF 何确保 确保      更新时间:2023-09-26

我有这个代码:

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 事件触发并尝试从服务器获取图像,但由于 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 以防止默认行为。 如果您希望页面地址在单词后立即更改,则可能需要在替换图像后在每个处理程序中放置位置重定向。