使用 jQuery.data() 设置元素文本不起作用

Setting text of element using jQuery .data() not working

我有一些 HTML table 单元格,这些单元格具有名为 data-rawdate 的数据属性,其中包含从服务器呈现的完整(和难看的)日期时间值。使用 jQuery,我想获取原始日期字符串,使用日期库(在本例中为 Moment.js)对其进行格式化,并将其设置为 <td>.[= 的文本21=]

这是一个简化版本,along with a demo

HTML:

<table>
  <tr>
    <td data-rawdate="1/6/2016 9:39:29 AM" class="dateField"></td>
    <td class="otherField"></td>
  </tr>
  <tr>
    <td data-rawdate="1/6/2016 9:58:31 AM" class="dateField"></td>
    <td class="otherField"></td>
  </tr>
  <tr>
    <td data-rawdate="1/6/2016 10:01:17 AM" class="dateField"></td>
    <td class="otherField"></td>
  </tr>
</table>

JavaScript:

$(document).ready(function() {

  $(".dateField").text(
    moment($(this).data("rawdate"), "M-D-YYYY h:m:s a")
        .format("M/D/YYYY")
  );

  //$(".dateField").text($(this).data("rawdate"));
});

起初我以为是库的问题,Moment.js,但后来我尝试跳过格式,简单地将元素的文本设置为$(this).data("rawdate")(参见JS的注释行) ,甚至那也没用。我什至尝试 .attr("data-rawdate") 而不是 .data("rawdate")——什么都没有。

有谁知道为什么 .text() 函数似乎不喜欢 .data() 函数?谢谢。

试试这个解决方案

$(document).ready(function() {

  $(".dateField").each(function(){
    $(this).text(moment($(this).data("rawdate"), "M-D-YYYY h:m:s a").format("M/D/YYYY")));
  }
});

您必须应用 each 方法并在 each 的回调函数中设置文本。请参见下面的示例:

$(document).ready(function() {

  $(".dateField").each(function(){
    $(this).text($(this).data("rawdate"));
  });
;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td data-rawdate="1/6/2016 9:39:29 AM" class="dateField"></td>
    <td class="otherField"></td>
  </tr>
  <tr>
    <td data-rawdate="1/6/2016 9:58:31 AM" class="dateField"></td>
    <td class="otherField"></td>
  </tr>
  <tr>
    <td data-rawdate="1/6/2016 10:01:17 AM" class="dateField"></td>
    <td class="otherField"></td>
  </tr>
</table>

所以你的问题代码:

$(".dateField").text(
    moment($(this).data("rawdate"), "M-D-YYYY h:m:s a")
        .format("M/D/YYYY")
  );

已更改为:

$(".dateField").each(function(){
    $(this).text($(this).data("rawdate"));
  });

没有moment(),但问题不在于此。主要思想是您如何访问元素并与之交互。