Wordpress - 将正文的数据属性值分配给变量

Wordpress - assigning a body's data attribute value to a variable

我正在使用 Wordpress,我正在尝试在我的自定义子主题中使用 functions.php 内的 javascript 获取数据属性的值并将其分配给变量。

页面呈现以下正文:

<body class="(...)" data-elementor-device-mode="desktop">

我正在尝试使用 functions.php 中的以下函数将 "desktop" 分配给一个变量:

<script type="text/javascript">
    var deviceType = document.body.getAttribute("data-elementor-device-mode");
    console.log(deviceType);
</script>

但是,查看控制台我得到 "null"。我究竟做错了什么?谢谢。

编辑:我已将代码切换为使用 HTML5 中的数据集功能。因此,我现在有以下内容:

  var body = document.body;
  console.log(body);
  var bodyDevice = body.dataset.elementorDeviceMode;
  console.log(bodyDevice);

第一个 console.log return 正文符合预期,但第二个 console.log 仍然 return "undefined"。

编辑 2:这一定是语法问题,因为以下内容

var bodyDevice = body.clientWidth;
console.log(bodyDevice);

将return body 元素的当前宽度(这解决了我的问题);不管怎样,为什么是

var bodyDevice = body.dataset.elementorDeviceMode;
console.log(bodyDevice);

不是 returning "desktop" 值?谢谢。

Elementor 在其初始化时插入由 JavaScript 设置的数据,请参阅第 271 行:https://github.com/elementor/elementor/blob/master/assets/dev/js/frontend/frontend.js

基本上您的代码没有返回任何内容,因为它是在 Elementor 插入数据集之前执行的...因此,在您的代码执行时没有 data-elementor-device-mode

尝试在页面加载后执行您的代码,例如:

window.onload = function() {
  var bodyDevice = document.body.dataset.elementorDeviceMode;
  console.log(bodyDevice);
};