js点集

239 阅读1分钟

1、jquery的event.stopPropagation()方法针对于事件委托时,当绑定在同一个content上面,会存在失效情况

<div class="content">
    <p class="a">
        <span class="b"></span>
    </p>
</div>

解决方案:

a、不要挂在同一个容器上,一个挂content,一个挂content1

$(".content").on("click", ".a", function(event){
    event.stopPropagation()
    alert(1);
})

$(".content1").on("click", ".b", function(event){
    event.stopPropagation()
    alert(1);
})
b、如果一定要挂在同一个容器上
$(".content").on("click", ".a", function(event){
    var target = event.target;
    if($(target).hasClass("a")){
        alert(1);
    }
})

$(".content").on("click", ".b", function(event){
    alert(1);
})

2、数组的indexOf()方法能查找对象,但是对象要先定义,否则查找不到,因为数组认为你是创建了一个新的对象;

var obj = {a:1};
arr = [obj,{b:2}];
var index1 = arr.indexOf(obj);//0
var index2 = arr.indexOf({b:2}});//-1

3、{} == {};//false;

var arr = [obj,{b:2}];
var item = {b:2};
function fIndexOf(arr, item){
    var index = -1;
    for(i = 0; i < arr.length; i++){
        if(obj[i] == item){
            index = i;
        }
    }
    return index;
}
fIndexOf(arr, item);//-1  {b:2}不等于{b:2}

4、外部方法(非实例)如何访问构造函数的原型,并保留this指针?

var name = "我是window的name";
var fn = window.fn || {};
fn.comment = function(){
    return new Comment();
}
//函数构造器
var Comment = function(){
    var self = this;
    this.name = "我是Comment的name";
    方法一:
    this.f2 = function(){
        self.f1.call(self);
    }
    ps:call会立即执行,用此方法可以保证在调用时执行
    
    方法二:
    this.f2 = self.f1.bind(self);
    ps:bind不会立即执行,this指向永久保存
    
    func1(this.f2);
    func2(this.f1);
}
Comment.prototype.f1 = function(){
    console.log(this.name);
}

var func1 = function(f){
    typeof f == "function" && f();//我是Comment的name
}

var func2 = function(f){
    typeof f == "function" && f();//我是window的name
}