单击JS加载图像 [英] JS load image on click

查看:57
本文介绍了单击JS加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加载图片,js需要获取链接网址并在屏幕上打印此图片.但这不起作用.

I need to load an image, js need to get link url and print this image on screen. But it is not working.

我的脚本出了什么问题?我该怎么做才能使其正常工作并加以改进?

What is wrong with my script? what can I do to make it work and improve it?

html

<div id=img></div>

<div id=loading></div>


<a href=http://png-5.findicons.com/files/icons/1580/devine_icons_part_2/128/my_computer.png class=postmini>Open image 1</a>
<br>
<a href=http://www.iconshock.com/img_jpg/BETA/communications/jpg/256/smile_icon.jpg class=postmini>Open image 2</a>

js

$(function() {
$(".postmini").click(function(){

var element = $(this);
var I = element.attr("href");

$("#loading").html('<img src="loader.gif" align="absmiddle">&nbsp;loading...');

$("#loading").ajaxComplete(function(){}).slideUp();
$("#img").append(I);

 });
});

https://jsfiddle.net/u6j2udzb/

和这个加载div,我需要做些什么才能使其正常工作?

and this loading div, what I need to do to make it work properly?

推荐答案

您丢失了很多东西,有很多不需要的东西.我已注释掉您不需要的物品.特别是您不需要加载,因为图像会在他们看到之前就在那里.但是,如果您仍然希望将其加载,则应将其加载到要加载的图像下方.因此它被图像覆盖.如果您愿意,我可以用它进行更新.

You are missing a lot and have a lot you don't need. I have commented out where you don't need items. In particular you don't need a loading because the image will be there before they see that. However, if you do want it still, you should be loading it underneath the image you are loading. So it gets covered by the image. I can update it with that if you'd like.

您缺少的是将href转换为图像源的实际代码,并且您没有删除定位标记的默认操作,因此单击该标记时不会尝试加载新页面.

What you are missing is actual code to turn the href into an image source and you are not removing the default action of the anchor tag so it doesn't try loading a new page when clicked.

$(".postmini").click(function(event){
event.preventDefault();
var element = $(this);
var I = element.attr("href");

//$("#loading").html('loading...');

//$("#loading").ajaxComplete(function(){}).slideUp();
// remove old image if it is already there.
$("#img").empty();
// create variable holding the image src from the href link
var img = $("<img/>").attr("src", I)

$("#img").append(img);

});

https://jsfiddle.net/3g8ujLvd/

这篇关于单击JS加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆