简体   繁体   English

jQuery函数仅运行一次

[英]jQuery function only being run once

Using the Moments.js library I'm attempting to grab the value of the datetime attribute from every time tag and output the time using natural language. 我试图使用Moments.js库从每个时间标记中获取datetime属性的值,并使用自然语言输出时间。

Given this: 鉴于这种:

<time datetime="2014-06-27"></time>

The Results would be: 结果将是:

<time datetime="2014-06-11">17 hours ago</time>

Using this: 使用这个:

$(document).ready(function(){
    var time = $('time'),
        date = moment(time.attr('datetime')),
        update = function(){
                   time.html(date.fromNow());
                 };

    update();
});

It works, but only for the first time element. 它有效,但仅适用于第一次。 All the additional time elements are also saying "17 hours ago". 所有其他时间要素也都说“ 17小时前”。

It's my guess that the function is only being run once on the first instance of time. 我猜想该函数仅在第一个时间实例上运行一次。

How can I make sure it's being run for each, and doing so efficiently? 我如何确保每个程序都在运行,并且效率高?

You need to loop through all the time tags. 您需要遍历所有时间标记。 Right now you are only applying it to the first instance of <time> . 现在,您仅将其应用于<time>的第一个实例。 Use jQuery .each() . 使用jQuery .each()

$(document).ready(function(){
    var time = $('time');

    time.each(function() {
        date = moment($(this).attr('datetime'));
        $(this).html(date.fromNow());
    });
});

jsFiddle Demo jsFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM