JavaScript之bom

window对象

间歇调用和超时调用

JavaScript是单线程语言,但它允许通过设置超时值和间歇时间来调度代码在特定的时刻执行,前者是在特定的时间过后执行代码,而后者则是每隔指定的时间就执行一次代码

// 超时调用
    let test = setTimeout(function () {
        console.log('我会进阿里的!')
    },2000)
    // 取消调用
    clearTimeout(test)

​ 在超时调用之前取消即可,否则没有意义。

间歇调用

 // 间歇调用
    let always = setInterval(function () {
        console.log('我会在2022年拥有最新的双门a5的')
    }, 1000)
     // 取消间歇调用
    clearInterval(always)

举个栗子: 使用超时调用模拟间歇调用

//  使用超时调用模拟间歇调用
    let num = 0;
    let max = 10;
    function incrementNumber() {
        num ++;
        console.log(num)
        if (num < max) {
            setTimeout(incrementNumber, 500)
        } else {
            alert('done')
        }
    }
    setTimeout(incrementNumber, 500)

location对象

​ document.location和window.location引用的是同一个对象。location提供了与当前窗口中加载的文档有关的信息,但是不止于此,还表现在它将URL解析成独立的片段,让开发人员可以通过不同的属性访问这些片段。接下来举例一些location的属性:

  1. hash '#content' 返回URL中的hash(#号后跟零或多个字符), 如果URL中不包含散列,则返回空字符串。
  2. host 'www.wrox.com:80' 返回服务器的名称和端口号(如果有)
  3. hostname 'www.wrox.com' 返回不带端口号的服务器名称
  4. Href 'http://www.baidu.com' 返回当前加载页面完整的URL。而location对象的toString()方法也返回这个值
  5. Pathname '/wileCDA/' 返回URL中的目录和(或)文件名
  6. port '8080' 返回URL中指定的端口号。如果URL中不包含端口号,则返回空字符串。
  7. Portocol 'http:' 返回页面使用的协议。通常是http:或https:
  8. Serach '?q=javascript' 返回URL的查询字符串。这个字符串以问号开头

查询字符串参数

demo如下

 function getQueryStringArgs() {
        let qs = (location.search.length > 0 ? location.search.substring(1) : '');
        // 如果存在查询参数,就去掉问号
        args = {};
        // 获取每一项
        let items = qs.length ? qs.split('&') : [];
        let item = null;
        let name = null;
        let value = null;
        items.forEach(i => {
            item = i.split('=');
            name = decodeURIComponent(item[0]);
            value = decodeURIComponent(item[1]);
            if (name.length) {
                args[name] = value;
            }
        })
        return args
    }
    let obj = getQueryStringArgs()
    console.log(args['_ijt']);

位置操作

​ 通过location去改变网页的位置,进行跳转等操作。举几个例子:

  1. Location.replace(): 跳转新页面,且无法返回
  2. Location.reload(): 刷新当前页面,速度取决因素较多,最好放在逻辑代码的最后。
posted @ 2020-05-23 22:03  Recklessz  阅读(132)  评论(0编辑  收藏  举报