1.事件监听:
document.getElementById('myButton').addEventListener('click', function() { alert('按钮被点击了!');});
2.动态创建元素:
var newDiv = document.createElement('div');newDiv.innerHTML = '这是新创建的div元素';document.body.appendChild(newDiv);
3.类名的操作:
var element = document.getElementById('myElement');element.classList.add('new-class'); // 添加类element.classList.remove('existing-class'); // 移除类element.classList.toggle('class-name'); // 切换类
4.查询DOM元素:
var elements = document.querySelectorAll('.my-class'); var element = document.getElementById('myId'); // 根据ID查询
5.处理表单数据:
var formData = new FormData(document.forms[0]); // 获取表单数据异步JavaScript和XML (AJAX) 请求:var xhr = new XMLHttpRequest();xhr.open('GET', 'ajax/test.html', true);xhr.onreadystatechange = function() { if (xhr.readyState ==4 && xhr.status == 200) { document.getElementById('myDiv').innerHTML = xhr.responseText; }};xhr.send();
6.使用JSON:
var jsonData = '{"name":"John", "age":30}';var obj = JSON.parse(jsonData); var myJSON = JSON.stringify(obj); // 将对象转换为JSON字符串
7.处理Cookie:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 UTC; path=/";var username = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*\=\s*([^;]*).*$)|^.*$/, "$1");
8.使用定时器:
setTimeout(function(){ alert("Hello"); }, 3000); clearTimeout(timer); // 清除定时器var timer = setInterval(function(){ console.log("Interval"); }, 3000); // 每3秒执行一次clearInterval(timer); // 清除定时器
9.处理字符串:
var str = "Hello, world!";var result = str.split(", "); // 分割字符串result = str.toUpperCase(); // 转换为大写result = str.substring(0, 5); // 截取字符串result = str.indexOf('world'); // 查找字符串
这些是原生JavaScript的基础知识点,每个点都可以展开讨论很多。根据具体需求,可以使用更多的JavaScript特性和方法。
该文章在 2024/12/26 10:44:08 编辑过