JavaScript常用方法

来自多彩世界 2020-06-02

主要介绍JavaScript中常用的事件和方法。

input事件

<input type="text" name="email" required value="Enter your email address"
  onfocus="this.value = '';" onblur="if(this.value == '') 
  this.value = 'Enter your email address';" />

一个原生的ajax请求

window.onload = function () {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("text").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "https://v1.hitokoto.cn/?encode=text", true);
        xmlhttp.send();
    }

解析json字符串

var text = '{"uid": 14, "name": "lx", "age": 14}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

获取当前时间戳

let timestamp = new Date().getTime();