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>
//事件捕獲 與冒泡segmentfault
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,則表示在事件捕獲階段調用處理函數。函數
詳細 轉自 : http://www.javashuo.com/article/p-djesifhj-ex.htmlthis
//綁定刪除文件 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); } }
http://tianfangye.com/2014/02/17/multiple-event-listeners/