html里面写js代码

在HTML中编写JavaScript代码是很常见的,你可以通过 <script> 标签将JavaScript代码嵌入到HTML文件中。

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript in HTML Example</title> </head> <body> <h1>JavaScript in HTML Example</h1> <p id="demo">This paragraph will change after executing JavaScript.</p> <script> // JavaScript code starts here // This code will change the content of the paragraph with id="demo" document.getElementById("demo").innerHTML = "Hello, World! This text is changed by JavaScript."; </script> </body> </html>

在这个示例中,<script> 标签包含了JavaScript代码,它会在页面加载时执行。在这个例子中,JavaScript代码使用 document.getElementById() 方法获取具有 id="demo" 的段落元素,并将其内容更改为 "Hello, World! This text is changed by JavaScript."。

当在HTML文件中编写JavaScript代码时,你可以利用各种JavaScript语法和功能来操作HTML文档的内容、样式和行为。

操作HTML元素的样式和属性:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Styling Example</title> <style> #demo { color: red; } </style> </head> <body> <h1>JavaScript Styling Example</h1> <p id="demo">This paragraph's color will change after executing JavaScript.</p> <script> // JavaScript code starts here // Change the color of the paragraph with id="demo" document.getElementById("demo").style.color = "blue"; </script> </body> </html>

事件处理:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Event Handling Example</title> </head> <body> <h1>JavaScript Event Handling Example</h1> <button id="myButton">Click me!</button> <script> // JavaScript code starts here // Add an event listener to the button document.getElementById("myButton").addEventListener("click", function() { alert("Button clicked!"); }); </script> </body> </html>

动态创建和修改HTML元素:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Dynamic HTML Example</title> </head> <body> <h1>JavaScript Dynamic HTML Example</h1> <div id="container"></div> <script> // JavaScript code starts here // Create a new paragraph element var paragraph = document.createElement("p"); paragraph.textContent = "This paragraph is dynamically created by JavaScript."; // Append the paragraph to the container div document.getElementById("container").appendChild(paragraph); </script> </body> </html>

这些示例展示了在HTML中编写JavaScript代码的一些常见用法,你可以根据需要使用JavaScript来操作和控制HTML文档中的各种元素和行为。