飞镖 - `querySelector`找不到元素
我想用DART替换JavaScript。
但这不是一个高级项目。这只是动态更改单个页面中的几个元素的问题。
对于初学者,我编写了以下HTML代码和DART代码,以根据其ID找到该元素并在控制台中显示文本。
<!-- index.html -->
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<p id="first-paragraph">Target.</p>
</body>
</html>
// index.dart
import 'dart:html';
void main() {
print(querySelector('#first-paragraph')?.innerText);
}
以下命令将文件转换为JavaScript文件。
dart compile js index.dart -o index.js -O0
但是,当我打开HTML文件时,控制台显示null
。
与上述代码非常相似的DART PAD HTML模式中的第一个代码似乎可行(在DART PAD上)。
为什么我的代码找不到元素?
谢谢。
I wanted to use Dart to replace JavaScript.
But it's not an advanced project. It's just a matter of dynamically changing a few elements within a single page.
For starters, I wrote the following HTML code and Dart code to find the element based on its ID and display the text in the console.
<!-- index.html -->
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<p id="first-paragraph">Target.</p>
</body>
</html>
// index.dart
import 'dart:html';
void main() {
print(querySelector('#first-paragraph')?.innerText);
}
The following command converts the file to a JavaScript file.
dart compile js index.dart -o index.js -O0
However, when I open the HTML file, the console shows null
.
The first code in Dart Pad HTML mode, which is very similar to the above code, appears to work (on Dart Pad).
Why can't my code find the element?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
谢谢您的评论。我从您的评论中记得,可以通过将脚本读数放置在
body
元素的末尾或使用window.addeventlistener
来使其能够按预期工作。我很ham愧地说我忘了做一些如此简单的事情。或者
Thank you for your comments. I remembered from your comments and was able to get it to work as expected by placing the script readout at the end of the
body
element or usingwindow.addEventListener
. I am ashamed to say that I forgot to do something so simple.or