使每个功能按第一个元素的顺序执行 [英] Make each function carry out in order of first element to last

查看:74
本文介绍了使每个功能按第一个元素的顺序执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用jQuery每个函数,但也需要它从第一个元素到最后一个元素都起作用.目前,似乎只是在选择符合条件的随机元素.

I need to use jQuery each function but also need it to work from the first element to the last. Currently it seems to just be choosing random elements that match the criteria.

这就是我所拥有的:

$(".ago-time").each(function(index) {
    var old_ts = $(this).data("ts2");
    $.get("phpscripts/get_new_time.php", {
        old_ts: old_ts,
        index: index
    }, function(result) {});
    alert(result);
});

indexold_ts发送到一个php文件,其输出类似于0: 1 minute ago.

The index and old_ts are sent off to a php file where the output will be something like 0: 1 minute ago.

我收到的警报不正确(从0到最高).将会是这样;

What I am getting in the alert is not in order (from 0 to highest). It will be something like this;

第一警报: 9:10分钟前

第二警报::2分钟前

第三警报:5分钟前8分钟

您可以看到警报不是按索引顺序排列的,因此每个功能必须随机选择ago-time.

As you can see the alerts are not in order of index so the each function must be selecting the ago-time's randomly.

推荐答案

each 进行迭代在jQuery对象上的匹配元素上顺序排列,但是这里的误解是另一个.

each does iterates sequentially over the matched elements over a jQuery object but the misunderstanding here is another.

$.get

$.get is a shorthand $.ajax function, that's an asynchronous HTTP request. The callback function, in this case:

function(result) {
  alert(result);
}

当您从服务器获得响应时,

被异步调用.

is called asynchronously as you get the responses from the server.

但是,从表面上看,这与您无关,并且在尝试调试服务器响应时会引起您的误解.

But, for what it seems, in your case this is irrelevant and a misunderstanding from you while trying to debug the server responses.

例如,在您的代码中,您可以简单地将响应从服务器接收到的响应设置为它们各自的DOM元素.

For instance, in your code you can simply set the responses as you receive them from the server to their respective DOM elements.

$(".ago-time").each(function(idx) {
  var $self = $(this);
  $.get("phpscripts/get_new_time.php", {
    old_ts: $self.data("ts2"),
    index: idx
  }, function(result) {
    $self.html(result);
  });
});

这篇关于使每个功能按第一个元素的顺序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆