使用PHP和jQuery预加载图像 – 逗号分隔数组?

所以我正在建立一个网站,它将在鼠标hover时使用大量动画GIF。 会有很多图像,我只想加载将在任何给定页面上使用的图像。 它正在使用WordPress,所以我可以使用条件标签只显示我在某个页面上需要的图像的URL。

我的问题是如何告诉浏览器/服务器需要预加载哪些图像。 我决定将HTML5数据属性添加到包含元素。

例如,我会在其中使用这个PHP的DIV:

<div id="home-container" class="preload" data-preload="">

哪个会在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 implode(", ", $images); } 

所以输出将是这样的:

 

然后我运行这个JavaScript:

 jQuery('.preload').each(function(){ var images = [ // Comma separated list jQuery(this).data('preload') ]; jQuery(images).each(function() { jQuery('').attr('src', this).addClass('preloaded').appendTo('body').hide(); }); }); 

问题是JavaScript不喜欢逗号分隔列表。 如果我只是写入URL,它工作正常。 那么有更好的方法来传递这些url吗? 或者更好的方式?

您需要通过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');