- 在文档中添加点击事件。当用户在文档任何地方点击时,在 id=”demo” 的 元素上输出 “Hello World”:
document.addEventListener("click", function(){document.getElementById("demo").innerHTML = "Hello World";});
语法:
addEventListener(‘eventType’,function(){},boolean)
- eventType 事件类型 click、mouseover、 …
- function(){} 要执行的函数
- boolean true 表示在捕获阶段触发,false 表示在冒泡阶段触发,默认是false
事件委托
- 利用事件冒泡的原理,将原本绑定给予子元素的时间绑定给父元素触发对应的事件
- 事件处理函数里面的this 事件绑定给谁,this就指向谁
- 阻止事件冒泡和浏览器的默认行为
e.stopPropagation() 阻止事件向父级传递
e.preventDefault() 阻止浏览器默认行为
例:
<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li></ul><a href="https://www.baidu.com">百度一下</a></body><script>var ul = document.querySelector('ul')var li = document.querySelectorAll('li')ul.onclick = function (e) {console.log(e.target)if (e.target.nodeName == 'LI') {var i = e.target.innerHTML// ul.removeChild(e.target)e.target.innerHTML = "";}}var newLi = document.createElement('li');newLi.innerHTML = 11;ul.appendChild(newLi);var a = document.querySelector('a')a.onclick = function (e) {e.preventDefault();//阻止浏览器默认行为}
