【问题标题】:add data attribute dynamically动态添加数据属性
【发布时间】:2019-12-07 20:26:13
【问题描述】:

我的html是

<div id="ctup-ads-widget-2" class="caption slide-heading "  data-x="380" data-y="80" data-speed="1800" data-start="1200" data-easing="easeOutExpo">Hui</div>

我正在尝试动态更改 dat=x 和 data-y 的值

我尝试了以下两种方法都不起作用。

<script>
$('#ctup-ads-widget-2').click(function() {

    $(this).attr("data-x", "580");
});
</script>

<script>
$('#ctup-ads-widget-2').click(function() {
    $(this).data('x') = "580";
});
</script>

<script>
window.onload = function() {
    var anchors = document.getElementById('ctup-ads-widget-2');
    for (var i = 0; i < anchors.length; i++) {
        anchors[i].setAttribute('data-x', '580');
        anchors[i].setAttribute('data-y', '30');
    }
}
</script>

控制台截图

错误截图

【问题讨论】:

  • $(this).data('x') = "580"; 在语法上是错误的......$(this).attr("data-x", "580"); 应该可以工作......你怎么说它不工作
  • 如果你使用data-api访问值那么需要使用$(this).data("x", "580");
  • api.jquery.com/data 参考这个
  • 很可能,您的 DOM 在脚本执行时没有加载。使用 jQuery document ready 或 window.onload 函数。

标签: javascript jquery html custom-data-attribute


【解决方案1】:

不能像这样使用它

$(this).data('x') = "580";//won't work

试试data()

 $(this).data("x","580"); //$(this).attr("data-x", "580") should also work

更新

将其附在$(document).ready..

$(document).ready(function(){
  $('#ctup-ads-widget-2').click(function() {
    $(this).data("x","580");
  });
})

【讨论】:

  • @Melvin Screenshot 没问题,但您需要告诉我们您在哪一行遇到了该错误。
  • @Melvin 你包含了 jQuery 吗?
  • 包含在页脚中.. 我已将脚本添加到页眉中.. 那是 pblm 吗?
【解决方案2】:

如果需要在元素上动态添加数据属性,

$("this").attr("data-x", "5");

可以使用。

从您的屏幕截图来看,很明显 jQuery 没有正确加载。 使用&lt;script&gt;标签在&lt;/body&gt;标签结束前加载jQuery文件。

示例:

<body>
...
..
<script src="js/jQuery.js"></script>
<script src="js/yourfile.js"></script>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 2011-06-23
    • 2017-01-13
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多