判断一个事件是否有某一个方法
//构造一个对象function Person(name){this.name=name;this.sayHi=function(){console.log("sayHIsss");}}var person=new Person("小明");if(person.sayHii){person.sayHii();}else if(person.sayHi){person.sayHi();}else{console.log("aa");}
入门火狐和谷歌支持
<!DOCTYPE html><html lang="en"><head> ?<meta charset="UTF-8"> ?<title>title</title></head><script >function ?my$(id){return document.getElementById(id);}//设置任意元素的中间的文本内容function setInnnerText(element,text) { ???if(typeof element.textContent=="undefined"){ ???????element.innerText=text; ???}else{ ???????element.textContent=text; ???}}</script><body><input type="button" value="创建一个p" id="btn"/>哈哈哈<div id=‘dv‘> </div><script>//添加多个绑定事件都可以执行ie8不支持 my$("btn").addEventListener("click",function () { ??console.log("你好皮"); },false); ?my$("btn").addEventListener("click",function(){ console.log("你好啊"); },false)//添加多个绑定事件火狐和谷歌不支持 my$("btn").attachEvent("onclick",function () { ??console.log("你好2"); },false); my$("btn").attachEvent("onclick",function () { ??console.log("我不好"); },false); ???</script></body></html>
为元素绑定事件兼容性代码
<!DOCTYPE html><html lang="en"><head> ?<meta charset="UTF-8"> ?<title>title</title></head><body><input type="button" value="按钮" id="btn"/><script src="common.js"></script><script> ?//为任意元素.绑定任意的事件, 任意的元素,事件的类型,事件处理函数 ?function addEventListener(element,type,fn) { ???//判断浏览器是否支持这个方法 ???if(element.addEventListener){ ?????element.addEventListener(type,fn,false); ???}else if(element.attachEvent){ ?????element.attachEvent("on"+type,fn); ???}else{ ?????element["on"+type]=fn; ???} ?} ?addEventListener(my$("btn"),"click",function () { ???console.log("哦1"); ?}); ?addEventListener(my$("btn"),"click",function () { ???console.log("哦2"); ?}); ?addEventListener(my$("btn"),"click",function () { ???console.log("哦3"); ?});// ?my$("btn")["on"+"click"]=function () {//// ?};// ?function Person(name) {// ???this.name=name;// ???this.sayHi=function () {// ?????console.log("您好啊");// ???};// ?}// ?var per=new Person("小明");// ?if(per.sayHii){//判断这个对象中有没有这个方法// ???per.sayHii();// ?}else{// ???console.log("没有这个方法");// ?}</script></body></html>
js中的绑定事件
原文地址:https://www.cnblogs.com/liushisaonian/p/9344543.html