for循环中的jQuery.load()
jQuery .load() within a for loop
我向服务器发送了一个ajax请求。然后我收到一个物体。对象看起来像这样:
{
"payload": {
"result": [
"http://example.com/img1.jpg",
"http://example.com/img2.jpg",
"http://example.com/img3.jpg",
"http://example.com/img4.jpg",
"http://example.com/img5.jpg"
]
}
}
然后我使用for循环遍历对象
if (typeof response.payload.result == 'object') {
var ln = response.payload.result.length;
var i;
if (ln > 0) {
for (i = 0; i < ln; i++) {
/* this shows i was increased for every iteration */
console.log(i);
var current_img = response.payload.result[i];
var img = $("<img />").attr('src', current_img)
.load(function () {
console.log(i);
/* this logs the last iteration 4 times */
$("#product-images").append(img);
});
}
}
}
我的问题是只创建了(1)个图像元素。执行此代码后附加到DOM的单个元素是数组中最后一个元素的值。为什么jQuery.load()
只在最后一次迭代中被调用?
if (typeof response.payload.result == 'object') {
var ln = response.payload.result.length;
var i;
if (ln > 0) {
for (i = 0; i < ln; i++) {
(function (n) {
var current_img = response.payload.result[i];
var img = $("<img />").attr('src', current_img)
.load(function () {
console.log(n);
$("#product-images").append(img);
});
})(i);
}
}
}
我想你错过了这一行的分号
var img = $("<img />").attr('src', current_img)
并且您尚未指定要在其中加载图像的元素的选择器。
相关文章:
- jQuery点击ON现在使用.load触发关闭
- 使用jquery.load('pageName')方法时,未从应用程序缓存加载Html页
- jQuery css可见性在load方法中不起作用
- 动态潜水高度jQuery.Load()不工作
- jQuery .load with variable as url
- jQuery.load()是另一个包含prism.js的页面
- jQuery and YUI load
- 使用.load()-jQuery缓慢加载内容
- for循环中的jquery.load()不起作用
- jQuery load()回调导致POST而不是GET
- css动画和jquery.load()在移动设备上断断续续
- jquery load()没有加载内容
- 在.load jquery中使用JSON返回的页面url
- 花哨的框回调函数 .load jquery
- 如何使用.load jQuery获取响应
- 函数内部页面使用load() jquery后不能正常工作
- 使用.load jquery时执行c#代码
- Load jQuery with RequireJS
- 是否有一种方法来加载一个函数从htm,你重新加载与.load()?JQuery
- 通过$.load jquery发送和获取数据