JS-Web-API(下)
zKing 2018-11-27 JavaScript
# 通用事件绑定
var btn = document.createElement('button');
btn.addEventListener('click',function(e){
console.log('clicked');
});
function bindEvent(elem,type,fn){
elem.addEventListener(type,fn);
}
var a = document.createElement('a');
bindEvent(a,'click',function(e){
e.preventDefault(); //阻止默认行为
alert('clicked');
});
btn.innerText = 'button';
a.innerText = 'a';
document.body.appendChild(btn);
document.body.appendChild(a);
# 事件冒泡
<body>
<div id="div1">
<p id="p1">激活</p>
<p id="p2">取消</p>
</div>
<div id="div2">
<p id="p3">取消</p>
<p id="p4">取消</p>
</div>
</body>
function bindEvent(elem,type,fn){
elem.addEventListener(type,fn);
}
var p1 = doucument.getElementById('p1');
var body = document.body;
bindEvent(p1,'click',function(e){
// 阻止冒泡,点击 p1 以后,事件会冒泡到 #div1,再到 body。
// 如果没有这行代码,弹窗显示激活后,还会显示取消。冒泡是逐层向上的
e.stopPropagation();
alert('激活');
});
bindEvent(body,'click',function(e){
alert('取消');
}
# 代理
<div id="div1">
<p id="p1">p1</p>
<p id="p2">p2</p>
<p id="p3">p3</p>
<p id="p4">p4</p>
<!--会随时新增更多的 a 标签 -->
</div>
// 在这里代理的意思是:
// 在 #div1 上绑定了事件,但是实际上是要对 p 标签进行事件操作。这里 #div1 就是代理商
var div1 = doucument.getElementById('div1');
div1.addEventListener('click',function(e){
var target = e.target
if(target.nodeName === 'P'){
console.log(target.innerText);
}
});
# 编写一个通用的事件监听函数
function bindEvent(elem,type,selector,fn){
if (fn == null){
fn = selector;
selector = null;
}
elem.addEventListener(type,function(e){
var target;
if(selector){ // 代理
target = e.target;
if(target.matches(selector)){
fn.call(target,e);
}
}else{ // 非代理
fn(e);
}
});
}
# Ajax
var xhr = new XMLHttpRequest();
xhr.open('GET','https://www.baidu.com/',true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
xhr.send();
# JSONP实现原理
<script>
window.callback = function(data){
console.log(data); // {x:100}
}
</script>
<script src="http://domin.com/api.js"></script>
<!-- 假设以上将返回 callback({x:100})-->