
批改狀態(tài):合格
老師批語(yǔ):
事件監(jiān)聽(tīng)調(diào)用addEventListener屬性。此監(jiān)聽(tīng)可以添加多個(gè)事件,且不會(huì)被覆蓋
刪除事件監(jiān)聽(tīng)調(diào)用removeEventListener屬性。
<button>按鈕</button>
<script>
const btn=document.querySelector("button");
const handle=()=>console.log(btn.innerHTML,"移除");
btn.addEventListener("click",handle);
btn.removeEventListener("click",handle);
</script>
不用調(diào)用,直接就執(zhí)行了。
const ev=new Event("click");
btn.addEventListener("click",function(){
console.log("自動(dòng)執(zhí)行了");
});
btn.dispatchEvent(ev);
兩種方式捕獲,冒泡
捕獲,從最外層元素逐級(jí)向內(nèi)直到事件的綁定者 事件為true;
2.冒泡:從目標(biāo)再由內(nèi)向外逐級(jí)向上直到最外層元素 事件為false;
<style>
#fu{
background-color: yellow;
width: 200px;
height: 200px;
}
#zi{
background-color: green;
width: 50px;
height: 50px;
}
</style>
<body>
<div id="fu">
<div id="zi">
</div>
</div>
<script>
const fu=document.querySelector("#fu");
const zi=document.querySelector("#zi");
fu.addEventListener("click",function(ev){
console.log(ev.currentTarget);
},true);
zi.addEventListener("click",function(ev){
console.log(ev.currentTarget);
},true);
</script>
</body>
如果元素太多,給父元素添加事件即可
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
<script>
const ul=document.querySelector("ul");
ul.addEventListener("click",function(ev){
ev.target.style.color="red";
});
</script>
留言板點(diǎn)擊留言刪除
<label for=""><input type="text" name="message"></label>
<ol id="list"></ol>
<script>
const msg=document.querySelector("input");
const list=document.querySelector("#list");
msg.onkeydown=ev=>{
//鍵盤事件中,key表示按下的鍵名
console.log(ev.key);
if(ev.key==="Enter"){
if(ev.currentTarget.value.length===0){
alert("內(nèi)容不能為空");
}else{
let str=`<li>${ev.currentTarget.value}</li>`;
list.insertAdjacentHTML("afterbegin",str);
//清空上條數(shù)據(jù)
ev.currentTarget.value=null;
}
}
}
//點(diǎn)擊某條留言則刪除
list.addEventListener("click",function(ev){
list.removeChild(ev.target);
});
</script>
//slice(start,end)取子串
let str="hello php.cn";
let res=str.slice(0,5);
//截取
substr(start,length)
res=str.substr(0,5);
//trim()刪除兩邊空格
let psw=" root ";
psw.trim();
//字符串長(zhǎng)度
str.length;
//查找字符串 某一個(gè)指定的字符首次出現(xiàn)的位置
str.indexOf("hello");
//替換內(nèi)容replace("被替換","替換后的內(nèi)容");
str.replace("hello","morning");
//大小寫轉(zhuǎn)換
str.toUpperCase();//轉(zhuǎn)為大寫
str.toLowerCase();//轉(zhuǎn)為小寫
//轉(zhuǎn)為數(shù)組
str.split(" ");使用空格分隔
//內(nèi)容匹配,查找字符串中特定的字符,找到則返回這個(gè)字符
str.match("hello");
//復(fù)制字符串repeat(次數(shù))
str.repeat(2);
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)