1 angularJS实现js控制input获取焦点
questionnaireDirectives.directive('setfocus', function(){
return {
restrict: 'EA',
replace: false,
scope: {
isBlur:"="
},
link:function(scope, element){
var isBlur = scope.isBlur;
scope.$watch("isBlur",function(newvalue, oldvalue) {
if (!oldvalue && newvalue ) {
setTimeout(function () {
element[0].focus();
}, 20);
}
});
}
};
});
//样式文件
<input is-blur="rule.isNameInputShow" setfocus ng-show="***">
解释1:也即当满足 oldvalue 为false,newvalue为 true 时,input才会自动获取焦点。
解释2:为什么要加延时函数,https://stackoverflow.com/questions/4798579/javascript-focus-function-not-working,防止在 input 元素渲染之前你调用了这个函数,setTimeout 是将函数添加到后台等待运行队列https://www.iteye.com/blog/p2world-1405227。
解释3:$watch的作用。$watch
是scope内置的函数,它的作用是用来监听数据的变化。类似事件监听,只是这里用来监听数据的变化。具体用法见https://blog.csdn.net/zcl_love_wx/article/details/51383548
2 如何实现回调 forEach 的循环中断(类似while下的break)
借助 some 和 every 回调函数,当需要中断时,在some 的回调函数中返回 true 其他情况可以什么都不返回(因为js默认返回false),在 every 回调函数中返回 false (其他情况什么都不返回,因为默认返回 true)。
例子:实现1-100循环,在等于50时中断循环。
arrr.some((ele, index) => {
if(index === 49){
console.log("我中断了");
return true;
}
});
3 sessionStorage的操作
增——setItem("key", value);
查——getItem("key");
删——removeItem("key");
注意:sessionStorage 保存、取操作前都是字符串的形式,
如果仅仅这样存储
var obj = {
name: "zsk",
age: 18
};
sessionStorage.setItem("mySessionStorage", obj);
会出现这种结果
正确的食用方法:
var obj = {
name: "zsk",
age: 18
};
//存储前保存为字符串
sessionStorage.setItem("mySessionStorage", JSON.stringify(obj));
//去除后,用parse转化为js能解析的对象
var obj_storage = JSON.parse(sessionStorage.getItem("mySessionStorage"));
4 空数组的 boolean 为 true
var arr = [];
!!arr //返回true
!!arr.length //返回false
5 关于数组元素是引用型变量的情况
var obj = {
name: "zsk",
age: 18
};
arr = new Array(10).fill(obj);
arr.forEach( (ele, index) => {
if(index === 5){
ele = null;
}
});
结果:
解释:引用型变量(对象)的变量名,保存的是堆内数据的地址值(地址值就相当于与一个数值,保存在函数的调用栈中),数组元素也是这样,虽然置ele为null,但是 arr[5] 仍旧保存着对 obj 的引用。如果对 obj 进行改变,arr数组中元素所执行的对象都会发生变化。
6 ng-class 的使用
<div ng-class="expression"> </div>
即可完成对div 样式进行控制。
7 构造函数下尽量不出现this
如下
window.onload = function () {
function MyClass () {
this.counter = 0;
this.length = 100;
this.beginBtn = document.getElementById("beginBtn");
this.stopBtn = document.getElementById("stopBtn");
this.beginBtn.onclick = function () {
console.log("beginBtn---->", this)
this.timer = setInterval(function () {
console.log("this.timer", this);
if (this.counter < this.max) {
console.log(this.counter++)
} else {
clearInterval(this.timer);
}
}, 100);
};
this.stopBtn.onclick = function () {
console.log("stopBtn----->", this)
clearInterval(this.timer);
}
};
var obj = new MyClass();
}
会一直返回 window 而不会返回理想的 obj 对象。点击按钮,其this 指向的确实button 的dom 对象。
解释:构造函数下的this就不是构造函数执行时,指向的对象了。
如果非要使用 this ,那么有下边几种途径:
- 使用call apply bind 方法
- 作为参数传入
- 将回调函数添加为this 的一个方法,再将其作为回调
- var that = this,借助变量的作用域链
- 闭包绑定this