当前位置:首页 > 行业动态 > 正文

HTML中使用JavaScript

在HTML中,JavaScript可通过` 标签嵌入,支持内联或外部引用,可置于 `中,用于实现交互功能(如表单验证、动态内容更新),常用事件监听(如click/load)绑定行为,配合DOM操作修改页面元素属性与结构

HTML中嵌入JavaScript的方法

方式 说明 示例代码
行内脚本 直接在HTML元素事件属性中写JS代码 <button onclick="alert('Hello')">点击</button>
内联脚本 <script>标签中编写JS代码 “`html


“` |
| 外部脚本 | 链接外部JS文件 | “`html

“` |
| ES6模块 | 使用`type=”module”`引入模块化JS | “`html

“` |

DOM操作核心方法

类别 常用方法 作用
元素选择 document.getElementById() 通过ID获取元素
document.querySelector() 通过CSS选择器获取元素
document.getElementsByClassName() 获取类名元素集合
节点操作 element.innerHTML 修改元素内部HTML
element.style 修改元素样式
parentNode.appendChild() 添加子节点
属性操作 element.setAttribute() 设置元素属性
element.getAttribute() 获取元素属性

事件处理机制

  1. 事件监听

    const btn = document.querySelector('.my-button');
    btn.addEventListener('click', function() {
      alert('按钮被点击');
    });
  2. 事件对象

    HTML中使用JavaScript  第1张

    document.addEventListener('keydown', function(e) {
      console.log(`按下了${e.key}键`);
    });
  3. 事件委托

    const list = document.querySelector('.item-list');
    list.addEventListener('click', function(e) {
      if(e.target.classList.contains('delete-btn')) {
        e.target.parentElement.remove();
      }
    });

表单验证示例

<form id="login-form">
  <input type="text" id="username" placeholder="用户名">
  <input type="password" id="password" placeholder="密码">
  <button type="submit">登录</button>
</form>
<script>
  const form = document.getElementById('login-form');
  form.addEventListener('submit', function(e) {
    e.preventDefault(); // 阻止表单提交
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    if(username === '' || password === '') {
      alert('请填写完整信息');
      return;
    }
    // 模拟登录验证
    if(username === 'admin' && password === '123456') {
      alert('登录成功');
    } else {
      alert('账号或密码错误');
    }
  });
</script>

加载

// 创建元素
const newItem = document.createElement('li');
newItem.textContent = '新列表项';
newItem.classList.add('list-item');
// 插入到DOM树
document.querySelector('.item-list').appendChild(newItem);
// 删除元素
const removeBtn = document.querySelector('.delete-btn');
removeBtn.addEventListener('click', function() {
  this.parentNode.remove();
});

AJAX与Fetch API

传统AJAX

const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.onload = function() {
  if(xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText));
  }
};
xhr.send();

现代Fetch

fetch('/api/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    document.querySelector('.container').innerHTML = JSON.stringify(data);
  })
  .catch(error => console.error('网络错误:', error));

注意事项

  1. 脚本位置<script>标签放在</body>前可避免DOM未加载完成的问题
  2. 作用域管理:建议使用const/let替代var,避免全局变量被墙
  3. 兼容性处理:需考虑老旧浏览器对ES6+语法的支持情况
  4. 性能优化:频繁操作DOM时建议使用DocumentFragment批量更新

相关问题与解答

Q1:如何通过JavaScript修改元素样式?
A1:可以通过element.style属性直接设置样式,

const box = document.querySelector('.box');
box.style.backgroundColor = 'blue';
box.style.width = '200px';

或使用classList切换CSS类:

box.classList.add('active');
box.classList.remove('hidden');

Q2:如何获取表单输入框的值?
A2:通过value属性获取输入值,

const input = document.querySelector('#username');
const value = input.value; // 获取当前值
input.value = 'new value'; // 设置新值

对于多选控件(如复选框/单选按钮):

const checkBox = document.querySelector('#agree');
if(checkBox.checked) {
  console.log('已勾选');
0