动态添加数据属性

问题描述 投票:1回答:2

我的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>

控制台屏幕截图

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS85RXhMcy5wbmcifQ==” alt =“在此处输入图像描述”>“ >>

错误屏幕截图

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS93OUtSai5wbmcifQ==” alt =“在此处输入图像说明”>“ >>

我的html是

Hui
我正在尝试...

不能

使用它
$(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");
  });
})

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

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

可以使用。

通过查看您的屏幕截图,很明显jQuery没有正确加载。在<script>标签结束之前,请使用</body>标签加载jQuery文件。

示例:

<body>
...
..
<script src="js/jQuery.js"></script>
<script src="js/yourfile.js"></script>
</body>
javascript jquery html custom-data-attribute
2个回答
3
投票

不能


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.