使用PHP和jQuery预加载图像 – 逗号分隔数组?
所以我正在建立一个网站,它将在鼠标hover时使用大量动画GIF。 会有很多图像,我只想加载将在任何给定页面上使用的图像。 它正在使用WordPress,所以我可以使用条件标签只显示我在某个页面上需要的图像的URL。
我的问题是如何告诉浏览器/服务器需要预加载哪些图像。 我决定将HTML5数据属性添加到包含元素。
例如,我会在其中使用这个PHP的DIV:
<div id="home-container" class="preload" data-preload="">
您需要通过deliminator逗号将URL字符串拆分为数组:
var images = jQuery(this).data('preload').split(',');
jQuery(this).data('preload')
返回一个字符串,你可以使用.split()
将该字符串拆分成一个数组: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/字符串/拆分
您还可以使用$.each()
使循环运行更快一些:
jQuery('.preload').each(function(){ var images = [ // Comma seperated list jQuery(this).data('preload') ]; jQuery.each(images, function() { jQuery('').attr('src', this).addClass('preloaded').appendTo('body').hide(); }); });
请注意,除了用于分隔data-attribute
不同url的逗号之外,您不应该有任何其他内容:
为什么不直接将列表放在Js数组中?
就像是 :
和你的PHP代码:
function preloadImages() { global $post; $templateURL = get_template_directory_uri(); $images = array(); if( is_page('test') ) $images[] = "'".$templateURL."/images/gifs-static/button-info-tab-close-off.gif'"; $images[] = "'".$templateURL."/images/gifs-animated/button-info-tab-close.gif'"; } return json_encode($images); }
让你的php将数据作为实际数组返回给元素,包含在[]
。 然后,当您使用.data()方法从data属性中提取它时,jquery会将其转换为实数数组。
DIV
码
var images = jQuery(this).data('preload');