【问题标题】:How to add a new data in data attribute如何在数据属性中添加新数据
【发布时间】:2017-11-16 02:24:08
【问题描述】:

我已经使用添加到我元素的数据属性中的把手进行了倒计时,但我想要添加当前年份。我使用的框架倒计时是接受“2017/06/14”这种数据倒计时格式的最终​​倒计时,我的 html 是这样的:

<div class="cd" id="cd" data-countdown="{{month}}/{{day}} {{time}}"></div>

我想要实现的是将第一个索引中的年份添加为

data-countdown="2017/{{month}}/{{day}} {{time}}"

到目前为止,这是我的 js 脚本:

var currentDate = new Date().getFullYear();

$('.cd').each(function(){
  //get each data-attribute
  var a = $(this).data("countdown");
  var b = a.split(" ");
  //add the current year to it
  b.unshift(currentDate);
  c = b[0]+'\/'+b[1]+'\/'+b[2];
  $(this).data("countdown", c); });

【问题讨论】:

  • 如果您使用.attr(),您的代码可以正常工作,例如$(this).attr("data-countdown", c);
  • 非 jquery 答案:this.dataset.countdown = c; - 相当于上述
  • @CarstenLøvboAndersen 出错,无法将 11/6 08:00:00 转换为日期对象。我还将 currentDate 转换为字符串仍然不起作用
  • @JaromandaX 它也不起作用。我想我应该只使用把手让用户输入当前年份,但这对他们没有帮助吧?
  • 所以,甚至 c = currentDate + '/' + a; 都没有(注意,无需转义 /

标签: javascript jquery jquery-countdown


【解决方案1】:

只需将当前年份添加到现有数据中即可。

$('.cd').each(function(){
  var getDataCountDown = $(this).data("countdown");
  var getYear = new Date().getFullYear(); // or whatever the year you want
  var newData = getYear + "/" + getDataCountDown;
  $(this).data("countdown", newData); 
});

更新

正如Jaromanda X所说,它不会改变DOM,如果我们需要改变DOM也意味着我们可以去

$(this).attr("data-countdown", newData);

而不是

$(this).data("countdown", newData);

【讨论】:

  • 这是我正在寻找的正确词!会尝试你的想法。
  • 这不会改变 DOM
  • 嘿,伙计们,它正在工作!是的,DOM 需要更新。所以我删除了元素中的data-countdown 数据并创建了一个新的,就像你告诉我的那样。然后使用attr() 附加它,感谢您的帮助!
【解决方案2】:

您的代码运行良好!

但正如您所说,您收到日期解析错误,您可以按照@Rajesh 的建议将年份附加到现有数据属性值,如下所示。

$('.cd').each(function(){ 
 $(this).data("countdown", new Date().getFullYear()+ "/" + $(this).data("countdown")); 
 alert($(this).data("countdown"))
});

使用$(this).data("countdown", c),您将无法通过检查看到更改,但如果您通过$(this).data("countdown") 提醒它,您可以看到它提醒更改的值,因为.data 管理元素的数据对象而不是DOM。

因此,如果您希望将来使用它,可以使用$(this).data("countdown", c),否则使用$(this).attr("data-countdown", c);

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多