javascript - 為什么無法實現表單原件失去焦點后改變提示的樣式?
問題描述
要實現一個表單,在輸入密碼一欄中如果沒有輸入或兩次輸入不一致則顯示提示,否則隱藏。但是提示始終出不來,求助是為什么呢?
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><link type='text/css' href='http://www.intensediesel.com/wenda/checkload.css' rel='stylesheet' /> <script type='text/javascript'>function checkEmpty(obj){ if(!obj.value)obj.nextSibling.style.display='block'; else obj.nextSibling.style.display='none'; } function checkPwd(obj){ var pwd = document.getElementById('pwd').value; var pwdAgain = obj.value; if(pwd != pwdAgain)obj.nextSibling.style.display='block'; elseobj.nextSibling.style.display='none';}</script><title>用戶登錄驗證</title></head><body><form class='bg'> <ul><li>用戶名:</li><li>輸入密碼:</li><li>確認密碼:</li> </ul> <p class='list'><p><input type='text'/></p><p><input type='password' onblur='checkEmpty(this)' /><span style='display:none'>密碼不能為空!</span></p><p><input type='password' onblur='checkPwd(this)'/><span style='display:none'>密碼不一致!</span></p><input type='submit' /> </p></form></body></html>
css代碼:
@charset 'utf-8';/* CSS Document */body{font-size:14px; font-family:'微軟雅黑';}body,p,ul,li{margin:0; padding:0; list-style:none;}.bg{ width:400px; height:180px; margin:50px; border:3px double #ccc; padding:40px; background:#CCC;}ul{float:left;}li{ text-align:right; height:50px;}.list{float:left;}p{ width:320px; height:50px; }span{ float:left; padding:0 0 0 10px; color:red;}#pwd{}
問題解答
回答1:找到你代碼中如下這段
<p><input type='password' onblur='checkEmpty(this)' /><span style='display:none'>密碼不能為空!</span></p><p><input type='password' onblur='checkPwd(this)'/><span style='display:none'>密碼不一致!</span></p>
請刪掉 <input/>和<span>之間的換行即可。
原因DOMElement.nextSibling屬性返回該節點下一個同級DOM元素,換行或者空格都算做一個#text類型的節點。之前你的代碼nextSibling返回的一個文本節點,在其上設置style屬性,當然不能達成你的需求。
如果不信,你還可以驗證一下:不改變你的html代碼,把腳本中 DOMElement.nextSibling換成 DOMElement.nextSibling.nextSibling 也能正常工作。
相關文章:
1. html5 - 有可以一次性把所有 css外部樣式轉為html標簽內style=" "的方法嗎?2. javascript - 原生canvas中如何獲取到觸摸事件的canvas內坐標?3. javascript - 如何將一個div始終固定在某個位置;無論屏幕和分辨率怎么變化;div位置始終不變4. html - vue項目中用到了elementUI問題5. python - 如何判斷爬蟲已經成功登陸?6. javascript - 求解答:實例對象調用constructor,此時constructor內的this的指向?7. javascript - 這不是對象字面量函數嗎?為什么要new初始化?8. javascript - vscode alt+shift+f 格式化js代碼,通不過eslint的代碼風格檢查怎么辦。。。9. javascript - 有什么比較好的網頁版shell前端組件?10. javascript - [js]為什么畫布里不出現圖片呢?在線等
