DOM绑定事件的三种方式

参考事件绑定原理

1. 在DOM中绑定。

在DOM中绑定有两种方式:

  • 直接在html中onXxxx = "jsCode"
  • 在html中onXxx = "handleName()",然后在js文件中定义
       
function handleName() {jsCode}
	<button onclick="alert('111')" type='button'></button>
	<button onclick="myClick()"></button>

2. 在js中绑定。

elementObj.onXxx = function(){}
elementObj.onclick=function() {
    alert('111')
}


3. 利用事件监听,但是事件监听要考虑到浏览器兼容性

Chrome、FireFox、Opera、Safari、IE9.0及其以上版本

elementObj.addEleventListener(type, handele, useCapture)  // useCapture是事件流,是否捕获

在IE8以及其以下版本中用

elementObj.attachEvent(type, handle)

	function addEvent(obj, type, handle) {
		try {
			obj.addEventListener(type, handle, false);
		} catch(e) {
			try {
				obj.attach('on' + type, handle);
			} catch(e) {
				obj['on' + type] = handle;
			}
		} 
	}


猜你喜欢

转载自blog.csdn.net/yangxiaoyanger/article/details/80331878