window.onload = function () { var lis = document.getElementById("list").getElementsByTagName("li"); for (var i = 0; i < lis.length; i++) { lis[i].addEventListener('click', li_click, false); } } function li_click() { var that = this; console.log(that); var span = that.getElementsByTagName("span")[0]; console.log(span.innerText); }
<script> var user = document.getElementById("user"); var pwd = document.getElementById("pwd"); //focus 获得焦点 user.addEventListener("blur", function () { //check_length(user); //传递参数 check_length.call(user); //把该函数的this 更改为user }, false); pwd.addEventListener("blur", function () { check_length(pwd); }, false); function check_length(obj) { var that = obj; var that1 =this; if (that.value.length < 1) { alert("空"); } console.log("user||pwd"); } </script>
//事件捕获 与冒泡
var dds = ul.getElementsByTagName("dd"); /* for (var i = 0; i < dds.length; i++) { dds[i].addEventListener("click", function () { //check(dds[i]); //传递参数 为未定义 check(this); //传递参数 }, true); } function check(obj) { var taht = obj; console.log(taht); } */ for (var i = 0; i < dds.length; i++) { dds[i].addEventListener("click", check, true); } function check(e) { var taht = e.target; console.log(taht); }
第三个参数默认值是false,表示在事件冒泡阶段调用事件处理函数;如果参数为true,则表示在事件捕获阶段调用处理函数。
详细 转自 : https://segmentfault.com/a/1190000005654451
JS addEventListener多次绑定同一事件,触发多次
//绑定删除文件 function bind_delfile() { var file_dels = document.getElementsByClassName("file_del"); for (var i = 0; i < file_dels.length; i++) { file_dels[i].addEventListener("click", del_file, true); } function del_file(e) { var that = e.target; that = that.parentNode.parentNode; var md5 = that.getAttribute("md5"); //检测对象是否相等 for (var j = 0; j < u_files.length; j++) { if (u_files[j].filemd5 == md5) { u_files.splice(j, 1); break; } } //此处多次绑定后 会触发 2次事件 that.parentNode && that.parentNode.removeChild(that); } }
addEventListener 多重监听问题
http://tianfangye.com/2014/02/17/multiple-event-listeners/