js 常用语法

176 阅读3分钟

1、元素获取

方法描述
getElementById()返回带有指定 ID 的元素。
getElementsByTagName()返回包含带有指定标签名称的所有元素的节点列表(集合/节点数组)。
getElementsByClassName()返回包含带有指定类名的所有元素的节点列表。
getAttribute()返回指定的属性值。
  • querySelector
  • querySelectorAll

2、元素操作

方法描述
appendChild()把新的子节点添加到指定节点。
removeChild()删除子节点。
replaceChild()替换子节点。
insertBefore()在指定的子节点前面插入新的子节点。
createAttribute()创建属性节点。
createElement()创建元素节点。
createTextNode()创建文本节点。
setAttribute()把指定属性设置或修改为指定的值。
document.getElementById("p1").innerHTML="新文本!";
document.getElementById("p1").innerHTML="<p>Hello Runoob!</p>";

3、css操作

  • 获取/设置 CSS 样式
const element = document.getElementById("example");
const style = window.getComputedStyle(element);

element.style.backgroundColor = "red";
  • 类名、样式名
const element = document.getElementById("example");
element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active"); // 如果存在类名 active ,则删除,否则添加

element.className = "test";
  • 尺寸、位置
const element = document.getElementById("example");
console.log(element.clientWidth);
console.log(element.clientHeight);
console.log(element.offsetWidth);
console.log(element.offsetHeight);

element.style.width = "200px";
element.style.height = "100px";

4、html事件

<button onclick="displayDate()">点我</button>

document.getElementById("myBtn").onclick=function(){displayDate()};

5、dom遍历

  1. parentNode - 获取当前元素的父元素。
  2. childNodes - 获取当前元素的所有子元素,包括文本节点。
  3. children - 获取当前元素的所有子元素,不包括文本节点。
  4. firstChild - 获取当前元素的第一个子元素,包括文本节点。
  5. lastChild - 获取当前元素的最后一个子元素,包括文本节点。
  6. firstElementChild - 获取当前元素的第一个子元素节点。
  7. lastElementChild - 获取当前元素的最后一个子元素节点。
  8. nextSibling - 获取当前元素的下一个兄弟元素,包括文本节点。
  9. previousSibling - 获取当前元素的上一个兄弟元素,包括文本节点。
  10. nextElementSibling - 获取当前元素的下一个兄弟元素节点。
  11. previousElementSibling - 获取当前元素的上一个兄弟元素节点。

6、xhr

XMLHttpRequest

是一个用于在Web应用中发送HTTP请求的技术,它允许客户端脚本与服务器进行通信,以请求数据或发送数据。以下是关于XMLHttpRequest的一些基本用法和关键点:

  1.  创建XMLHttpRequest对象‌:首先,需要创建一个XMLHttpRequest对象。这可以通过调用new XMLHttpRequest()来实现。

    javascriptCopy Code
    let xhr = new XMLHttpRequest();
    
  2. 设置请求方法和URL‌:使用xhr.open()方法来设置请求的类型(GET、POST等)和请求的URL。

    javascriptCopy Code
    xhr.open('GET', 'https://example.com/data');
    
  3. 设置请求头‌:使用xhr.setRequestHeader()方法来设置HTTP请求头。这个方法必须在xhr.open()xhr.send()之间调用。

    javascriptCopy Code
    xhr.setRequestHeader('Content-Type', 'application/json');
    
  4. 发送请求‌:使用xhr.send()方法来发送请求。对于GET请求,通常不需要发送任何数据;对于POST请求,可以发送JSON、表单数据等。

    javascriptCopy Code
    xhr.send(null);  // 对于GET请求,send方法的参数通常为null
    // 对于POST请求,可能会这样发送数据:
    // xhr.send(JSON.stringify({ key: 'value' }));
    
  5. 处理响应‌:通过监听xhr.onreadystatechange事件来处理服务器的响应。当xhr.readyState变为4且xhr.status为200时,表示请求成功完成,此时可以访问xhr.responseTextxhr.response来获取响应数据。

    javascriptCopy Code
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                console.log(xhr.responseText); // 打印响应文本内容
            } else {
                console.error('Request failed: ' + xhr.status);
            }
        }
    };
    
  6. 设置响应类型‌:使用xhr.responseType属性来设置服务器响应的数据类型,如"text"、"arraybuffer"、"blob"等。这可以在请求发送前设置。

    javascriptCopy Code
    xhr.responseType = 'json'; // 期望服务器返回JSON格式的数据
    
  7. 获取响应头‌:使用xhr.getAllResponseHeaders()xhr.getResponseHeader('header-name')来获取响应的HTTP头部信息。

XMLHttpRequest提供了丰富的API来处理HTTP请求和响应,使得在浏览器环境中进行网络通信变得相对简单。通过这些方法,可以构建出功能丰富的Web应用,实现数据的异步加载和更新‌

fetch

fetch('https://api.github.com/users/ruanyf')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log('Request Failed', err));

7、 HTML DOM 实例