JavaScript 开发经验之谈

Ø  简介

JavaScript(简称:JS)是前端开发的重要掌握技术之一,动态加载、数据处理、事件响应、用户交互、服务端通讯等都需要使用 JS 来完成,以下是日常开发常用技术总结:

 

1.  移除元素属性

通过getAttribute()setAttribute()removeAttribute()方法,分别获取、设置、移除元素的特性(不推荐使用,前两个方法IE6/7中有异常,第三个方法IE6不支持,设置自定义特性时可以使用)

getAttribute()方法,用于获取元素属性。接受一个参数,即要获得元素的属性名

setAttribute()方法,用与设置元素属性。接受两个参数,即要获得元素的属性名和属性值

removeAttribute()方法,用于移除元素的属性。接受一个参数,即要移除元素的属性名

 

2.  阻止默认事件

1)  event.preventDefault();

2)  阻止默认事件和事件冒泡

e.click = function(){

    return false;

}

3)  阻止一个事件冒泡

event.stopPropagation();

4)  JS event.keyCode

参考:http://unixpapa.com/js/key.html

5)  onkeydown事件早于onkeyparss

 

3.  mousedownmouseupclick 事件的执行顺序

mousedown 最先执行,mouseup 其次执行,click 最后执行

 

4.  查看某一个函数所在文件,在浏览器中点击函数即可查看

var f = recordLog.prototype.constructor;

console.log(f);

 

5.  JS 判断是否为对象

1)  使用 toString() 方法

let obj = {}

Object.prototype.toString.call(obj) === '[Object Object]'

2)  使用 constructor 属性

let obj = {}

obj.constructor === Object

3)  使用 instanceof 关键字

注意:使用instanceof对数组进行判断也是对象

let obj = {}

obj instanceof Object //true

let arr = []

arr instanceof Object //true

4)  使用 typeof 关键字

let obj = {}

typeof obj === Object

// 根据typeof判断对象也不太准确

表达式                       返回值

typeof undefined           'undefined'

typeof null                'object'

typeof true                'boolean'

typeof 123                 'number'

typeof "abc"               'string'

typeof function() {}       'function'

typeof {}                  'object'

typeof []                  'object'

 

6.  JS 实现复制

function copyText(text) {

    let transfer = document.createElement('input');

   document.body.appendChild(transfer);

    transfer.value = text;

    //transfer.focus();

    transfer.select();

    if (document.execCommand('copy')) {

        document.execCommand('copy');

    }

    //transfer.blur();

   document.body.removeChild(transfer);

    $.toptip('复制成功', 'success');

}

 

7.  遍历JS 对象的所有成员

for(var k in document)

    document.write("document." + k + " = " + document[k] + "<br/>");

var obj = xxx;

for (var k in obj)

console.log("obj." + k + " = " + obj[k]);

 

8.  原生 JS 设置会话Cookie(Session Cookie)

function setSessionCookie(name, value, cookiePath) {

    var isIE = !-[1,];//判断是否是ie核心浏览器

    if (isIE) {

        if (value) {

            var expire = "; expires=At the end of the Session";

            var path = "";

            if (cookiePath != null) {

                path = "; path=" + cookiePath;

            }

            document.cookie = name + "=" + escape(value) + expire + path;

        }

    } else {

        if (value) {

            var expire = "; expires=Session";

            var path = "";

            if (cookiePath != null) {

                path = "; path=" + cookiePath;

            }

            document.cookie = name + "=" + escape(value) + expire + path;

        }

    }

}

function getCookie(name) {

    var strcookie = document.cookie;//获取cookie字符串

    var arrcookie = strcookie.split("; ");//分割

    //遍历匹配

    for (var i = 0; i< arrcookie.length; i++) {

        var arr = arrcookie[i].split("=");

        if (arr[0] == name) {

            return arr[1];

        }

    }

    return "";

}

注意:浏览器记住历史记录时将失效;微信浏览器好像不支持

 

9.  cookielocalStoragesessionStorage 的使用

1)  浏览器客户端除了使用cookie 存储客户端数据,还可以使用localStoragesessionStorage 存储数据;

2)  sessionStorage 存储的数据在本次会话中有效,会话结束时会自动清除数据;

 

10. JS中的12种循环遍历方法

参考:https://www.jb51.net/article/141193.htm

 

11. JS的事件监听机

参考:http://blog.sina.com.cn/s/blog_51048da70101elgd.html

 

12. 对某个元素进行事件触发时,比如点击事件时,想获取这个事件对象,这时候可以通过如下方式获取

<input type="button" value="测试" onclick="test()" />

function test(e){

    const event = e || window.event

    console.log(event, 'event')

}

13. 带参数的事件函数怎么获取事件对象

<input type="button" value="测试" onclick="test(event,2)" />

function test(e, other){

    const event = e || window.event

    console.log(event, other, 'event')

}

注意:在传入你自己的参数前,先把event放在第一个参数传入(注意参数名event和传入必须是第一个参数位置),然后就可以在该事件回调函数中获取事件对象,传统获取 e || window.event

 

14. JSON对象与字符串互相转换

在数据传输过程中,JSON是以文本,即字符串的形式传递的,而JS操作的是JSON对象,所以,JSON对象和JSON字符串之间的相互转换是关键。

1)  JSON 字符串转为JSON 对象

//json字符串(注意:必须为""不能为''

var jsonStr = '{ "Id": 10, "Name": "张三丰", "Sex": "" }';

 

//1. 使用window.JSON.parse()方法

var jsonObj1 = window.JSON.parse(jsonStr);

alert(jsonObj1.Id);

 

//2. 使用window.eval()方法

var jsonObj2 = window.eval("(" + jsonStr + ")");

alert(jsonObj2["Name"]);

 

//3. 使用string.parseJSON()方法

var jsonObj3 = jsonStr.parseJSON();

alert(jsonObj3.Sex);

 

注意:如果jsonStr本来就是一个JSON对象,那么使用eval()函数转换后(哪怕是多次转换)还是JSON对象,但是使用parseJSON()函数处理后会有问题(抛出语法异常)。

 

2)  JSON 对象转为JSON 字符串

//json对象

var jsonObj = { "Id": 20, "Name": "王美丽", "Sex": "" };

 

//1. 使用window.JSON.stringify()方法

var jsonStr1 = window.JSON.stringify(jsonObj);

alert(jsonStr1);

 

//2. 使用object.toJSONString()方法

var jsonStr2 = jsonObj.toJSONString();

alert(jsonStr2);

 

注意:上面的几个方法中,除了eval()函数是js自带的之外,其他的几个方法都来自json.js包。新版本的JSON 修改了API,将JSON.stringify() JSON.parse() 两个方法都注入到了Javascript 的内建对象里面,前者变成了 Object.toJSONString(),而后者变成了String.parseJSON()。如果提示找不到toJSONString()parseJSON()方法,则说明您的json包版本太低。

posted @ 2022-03-27 11:43  Abeam  阅读(136)  评论(0编辑  收藏  举报