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.lshqa.cn/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. Span標簽2. css - 求推薦適用于vue2的框架 像bootstrap這種類型的3. docker-machine添加一個已有的docker主機問題4. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?5. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””6. SessionNotFoundException:會話ID為null。調用quit()后使用WebDriver嗎?(硒)7. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?8. angular.js使用$resource服務把數據存入mongodb的問題。9. redis啟動有問題?10. css - 關于div自適應問題,大家看圖吧,說不清
