简体   繁体   English

QuerySelector 在 Rails Webpacker 中不起作用

[英]QuerySelector Not Working in Rails Webpacker

I have the following JavaScript loaded into Webpacker:我将以下 JavaScript 加载到 Webpacker 中:

'use strict';

(function() {
  alert("This shows up.");
  var someObject = document.querySelectorAll('[data-toggle="thing"]');
})();

I know that the file is loaded into Webpacker correctly and is executed because I see the alert This shows up.我知道该文件已正确加载到 Webpacker 并被执行,因为我看到了警报This shows up. . . However, when I go into the console, someObject is an empty array despite the page containing an object with the data-toggle attribute.但是,当我 go 进入控制台时,尽管页面包含具有data-toggle属性的 object,但someObject是一个空数组。

I don't see any errors in the console to help diagnose the issue.我在控制台中没有看到任何有助于诊断问题的错误。

I am guessing that the problem involves the script executing before the page is loaded?我猜这个问题涉及在页面加载之前执行的脚本? However, I'm not sure how to remedy that situation when using Rails 6 with Webpacker...但是,当使用带有 Webpacker 的 Rails 6 时,我不确定如何解决这种情况......

Any assistance would be hugely appreciated!任何帮助将不胜感激!

You may need to wrap your code in an event listener callback that will execute when the DOM is loaded .您可能需要将代码包装在事件侦听器回调中,该回调将在 DOM 加载时执行 This may be the case if your script tag is in the <head> ;如果您的脚本标签位于<head>中,则可能是这种情况; it executes before the rest of the page is loaded.它在页面的 rest 加载之前执行。

window.addEventListener('DOMContentLoaded', (_event) => {
  let someObject = document.querySelectorAll('[data-toggle="thing"]');
});

You also don't necessarily need to wrap your code in an IIFE (ie, (function() { })() because each file in webpack is (typically) treated as module with its own function scope.您也不一定需要将代码包装在 IIFE 中(即(function() { })() ,因为 webpack 中的每个文件(通常)都被视为具有自己的 function Z31A1FD140BE4BEF2D18A81.2 的模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM