简体   繁体   中英

Flask JavaScript/HTML Scripts Not Working

I have a flask web application I am creating( also using Angular CLI), and I have a button. I am trying to use JavaScript to conduct an action on the button click but for whatever reason I can't get the JavaScript to work.

However when I copy the java Script into a completely different simple flask project (that I downloaded from online), it works fine?

Does anyone know if I have to do something in my flask project to get the javascript working?

I read somewhere it has to do with the way i run the flask app ? (0.0.0.0 vs localhost) but im not sure

Here's the code I am trying to use:

<!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>

You passed function result as an argument instead of function instead. Use

onclick="myFunction"

But if you want do it in a professional way you should do this:

<!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>

And using innerHTML to inserting data isn't the best option too. In javascript you can create DOM elementr programaticaly.

Try this, if none of the console.log's show up then its a issue with how it's compiled

 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"; } }) 

Try from a 'static' folder in the root directory. Literally call it static and then place a js file inside. Then in the html try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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