PhotoSwipe 动态ajax加载图片

开发JqueryMobile的时候需要用到PhotoSwipe插件来显示图片。

下载地址:

http://www.photoswipe.com/

 

如何让程序能动态加载图片呢,参照demo改写了一下,在初始化的时候先加载图片,然后再实现效果:

 

<script type="text/javascript">
var options = {};
var instance;
(function(window, $, PhotoSwipe) {
	$(document).ready(function() {
		loadDatas();
	});

        /*初始化插件*/
	function bindPhotoSwipe() {
		instance = $("#Gallery a").photoSwipe(options);
		var size = $("#Gallery a").length;
		// onDisplayImage
		instance.addEventHandler(PhotoSwipe.EventTypes.onDisplayImage,
				function(e) {
					console.log("Number of images loaded so far: "+ instance.cache.images.length);
				});
	}
	/*
		加载数据
	*/
	 function loadDatas(){
	   var url = "./action/GetPicAction.do";
	   var content = '';
	    $.get(url,function(response){
	   		$.each(response,function(index,item){
	   			content += "<li><a href=\""+item.fullurl+"\" rel=\"external\"><img src=\""+item.thumburl+"\" /></a></li>";
	   		});
	   		$("#Gallery").append(content);
		},"json"); 
		
		bindPhotoSwipe();
	};
		/*
			解绑
		*/
		function detatch(){
			PhotoSwipe.detatch(instance);
			PhotoSwipe.activeInstances = [];	
		}
}(window, window.jQuery, window.Code.PhotoSwipe));
</script>

 

程序看起来是没什么问题,图片也能出来,但是就是没有图片预览效果。

用firebug调试出现下面的错误:

uncaught exception: Code.PhotoSwipe.createInstance: No images to passed.

在构造插件结构的时候没加载进图片。

这个问题折腾了好久,最终想到是不是同步异步的问题,于是在发送ajax请求的时候加了一句,关掉异步请求。

 $.ajaxSettings.async = false;

抱着试一试的态度,谁知结果还真实现了。

 

附上后台生成的json字符串:

[{"fullurl":"images/full/1.jpg","thumburl":"images/thumb/1.jpg"},{"fullurl":"images/full/2.jpg","thumburl":"images/thumb/2.jpg"},{"fullurl":"images/full/3.jpg","thumburl":"images/thumb/3.jpg"},{"fullurl":"images/full/4.jpg","thumburl":"images/thumb/4.jpg"},{"fullurl":"images/full/5.jpg","thumburl":"images/thumb/5.jpg"},{"fullurl":"images/full/6.jpg","thumburl":"images/thumb/6.jpg"},{"fullurl":"images/full/7.jpg","thumburl":"images/thumb/7.jpg"},{"fullurl":"images/full/8.jpg","thumburl":"images/thumb/8.jpg"},{"fullurl":"images/full/9.jpg","thumburl":"images/thumb/9.jpg"}]

 附上页面代码:

<div data-role="page" id="pic_index" class="gallery-page">
		<div data-role="header">
			<h1>美女图片</h1>
		</div>
		<div data-role="content">
			<ul class="gallery" id="Gallery">
			</ul>
		</div>
		<div data-role="footer">
			<h4>@飘渺</h4>
		</div>

	</div>

 

 

 

你可能感兴趣的:(PhotoSwipe 动态ajax加载图片)