4

第一次发帖。所以我必须在一个看起来像这样的元素中格式化一些文本

<div class="entry-time">
  2012-05-30T20:11:06+00:00 
</div>

我正在尝试使用moment.js将其格式化为更具可读性的内容。我只能从前端使用 javascript 执行此操作。我写了一个看起来像这样的函数。

$(document).ready(function() {
    function formatDate(date) {
        formattedDate = date.text();
        var d = moment(formattedDate, "YYYY-MM-DDTHH:mm:ss");
        $(date).html( d.format("dddd, MMMM Do YYYY, h:mm:ss a"));
    };

    formatDate($('.entry-date'));
});

如果有一个元素,则此方法有效,但当有多个元素时,它将所有内容格式化为一个日期。我知道这与 jQuery 拉入一组元素有关,但我不知道如何使用 entry-date 类对每个元素执行我所做的操作。

任何人都可以帮忙吗?先感谢您。

4

5 回答 5

6

At the heart of what's wrong is that the jQuery .text() method gets "the combined text contents of each element in the set of matched elements, including their descendants" (api.jquery.com/text) rather than iterating over the set of elements as you intend.

Something like this should work, passing a function into the jQuery .html() setter method:

$(".entry-date").html(function(index, value) {
    return moment(value, "YYYY-MM-DDTHH:mm:ss").format("dddd, MMMM Do YYYY, h:mm:ss a");
});
于 2012-05-31T04:41:28.127 回答
2

您需要使用 jquery 的 .each 方法遍历每个匹配项:

$(date).each(function(){  Format date here  });

这将进入您现在现有的函数 formatDate。

于 2012-05-31T04:31:22.307 回答
1

You will want to loop through the elements passed to the function. This could be done with a $.each() in jQuery. Here's a quick example:

http://jsfiddle.net/n1ck/QQYq2/1/

$(function(){
    function formatDate(dates) {
        dates.each(function(){
            //get date
            formattedDate = $(this).text();

            //format it
            var d = moment(formattedDate, "YYYY-MM-DDTHH:mm:ss");

            //replace it
            $(this).html(d.format("dddd, MMMM Do YYYY, h:mm:ss a"));
        });
    };

 formatDate($('.entry-time'));
});
​
于 2012-05-31T04:43:25.687 回答
0

Based on your current code you can modify your formatDate function like this

 $(document).ready(function() {
    function formatDate(date) {
      date.each(function(){
        var formattedDate = $(this).text();
        var d = moment(formattedDate, "YYYY-MM-DDTHH:mm:ss");
        $(this).html( d.format("dddd, MMMM Do YYYY, h:mm:ss a"));

      });
  };

 formatDate($('.entry-time'));
});

And you actual class name is entry-time but you are calling like formatDate($('.entry-date')); which will get nothing as the class entry-date doesn't exist.

Working Fiddle​</p>

于 2012-05-31T04:37:46.030 回答
0

You have to use each because your selector is a class(since you used '.') which can be used with multiple DOM's as well..so may be your jquery thing is returning an array which is to be traversed using each.

$('.entry-date').each(function(){
   formatDate($(this).val());//if it is a text box
});

OR

$('.entry-date').each(function(){
   formatDate($(this).text());//if it is a label
});
于 2012-05-31T04:38:32.497 回答