繁体   English   中英

Flask JavaScript / HTML脚本不起作用

[英]Flask JavaScript/HTML Scripts Not Working

我有一个正在创建的flask Web应用程序(也使用Angular CLI),并且有一个按钮。 我正在尝试使用JavaScript对按钮单击进行操作,但是由于任何原因,我都无法使JavaScript正常工作。

但是,当我将Java脚本复制到完全不同的简单flask项目(我是从在线下载的)时,是否可以正常工作?

有谁知道我是否必须在flask项目中做点什么才能使javascript工作?

我在某处阅读了与运行flask应用程序的方式有关的信息? (0.0.0.0 vs localhost)但我不确定

这是我要使用的代码:

<!DOCTYPE html>
<html>
<body>

<h1>The onclick Event</h1>

<p>The onclick event is used to trigger a function when an element is clicked on.</p>

<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}
</script>

</body>
</html>

您将函数结果作为参数而不是函数传递。 采用

onclick="myFunction"

但是,如果要以专业的方式进行操作,则应该这样做:

<!DOCTYPE html>
<html>
<body>

<h1>The onclick Event</h1>

<p>The onclick event is used to trigger a function when an element is clicked on.</p>

<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button>Click me</button>

<p id="demo"></p>

<script>
document.querySelector('button').addEventListener('click', myFunction)
function myFunction() {

  document.getElementById("demo").innerHTML = "Hello World";
}
</script>

</body>
</html>

使用innerHTML插入数据也不是最佳选择。 在javascript中,您可以通过编程方式创建DOM elementr。

如果没有显示console.log,请尝试此操作,这是有关如何编译的问题

 document.addEventListener('DOMContentLoaded',()=>{ console.log('loaded) let btn = document.querySelector('button') btn.addEventListener('click', myFunction) function myFunction(e) { console.log(e); document.getElementById("demo").innerHTML = "Hello World"; } }) 

从根目录中的“静态”文件夹尝试。 从字面上称它为静态,然后将js文件放入其中。 然后在html中试试这个

暂无
暂无

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

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