[英]Cloning in-memory image in JavaScript /jQuery
This is probably a really simple one but I couldn't find the answer. 这可能是一个非常简单的方法,但我找不到答案。
I have the following JavaScript/jQuery code where I am trying to create loading messages: 我在尝试创建加载消息的地方使用以下JavaScript / jQuery代码:
// preload an image to use for dynamic loading icon whenever requested
$(document).ready(function() {
var loadingIcon = document.createElement('img');
loadingIcon.src = '../images/ajax-loader.gif';
window.loadingIcon = loadingIcon; // chache in global var
});
I wanted to cache the image on load so I'm not requesting it each time I want a loading message. 我想在加载时缓存图像,因此我每次都不需要加载消息时都不需要它。 Am I actually acheiving this with the above code? 我实际上通过上面的代码实现了吗?
The idea is that there's a lot of dynamic content on the page, and at any time I might have several different loading icons active. 这个想法是页面上有很多动态内容,并且在任何时候我可能都会激活几个不同的加载图标。
I add the loading icon wherever with: 我随处添加加载图标:
$('#myElem').appendChild(window.loadingIcon);
This doesn't actually work though, when I try to show a new loading icon, it just moves the previous one, so I can't have more than one on the page at a time. 但是,这实际上并不起作用,当我尝试显示一个新的加载图标时,它仅移动了前一个图标,因此一次不能在页面上显示多个图标。
I'm assuming I need to clone the element? 我假设我需要克隆元素?
I tried to wrap the element in a jQuery object to use clone with $(window.loadingIcon).clone()
but that didn't work (the function errored). 我试图将元素包装在jQuery对象中,以将克隆与$(window.loadingIcon).clone()
但是没有用(函数错误)。
You could clone the element, yes. 您可以克隆元素,是的。 But you can just as well create a new <img>
element. 但是您也可以创建一个新的<img>
元素。 If the image src has already been loaded by the browser, the image data will be cached and no further network-load will occur. 如果浏览器已经加载了图像src,则图像数据将被缓存,并且不会再发生网络负载。 You don't need to cache the element itself to cache the resource it's pointed at. 您不需要缓存元素本身就可以缓存其指向的资源。
Try creating the image as a jQuery object: 尝试将图像创建为jQuery对象:
var $loadingIcon = $('<img src="../images/ajax-loader.gif" />');
And then you should be able to clone it when you need to use it: 然后,当您需要使用它时,您应该能够克隆它:
$('#myElem').append( $loadingIcon.clone() );
javascript has a native cloneNode
method, at least in IE7, which is all I have at the moment. javascript至少在IE7中具有本机cloneNode
方法,这是我目前所拥有的。 I'm pretty sure it's cross browser. 我很确定这是跨浏览器。
this should do what you want: 这应该做你想要的:
$('#myElem').appendChild(window.loadingIcon.cloneNode());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.