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

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

本文关键字:元素 文本 不起作用 设置 jQuery data 使用      更新时间:2023-09-26

我有一些HTML表格单元格,它们具有称为data-rawdate的数据属性,其中包含从服务器呈现的完整(且外观丑陋)的日期时间值。使用 jQuery,我想获取原始日期字符串,使用日期库(在本例中为 Moment.js)对其进行格式化,并将其设置为<td>的文本。

这是一个简化版本,以及一个演示。

.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()函数?谢谢。

您必须应用每个方法并在 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(),但问题不在其中。主要思想是你如何访问元素和与元素交互。

试试这个解决方案

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