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://m.baoyu77737.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. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. javascript - 求賜教:網易郵箱Web端模擬登錄看信的加密參數_ntes_nnid、_ntes_nuid3. javascript - 使用angular 的ui-sref 中出現了中文參數,點擊跳轉后瀏覽器的地址欄里出現轉義后的%AE....%a%44. java - ConcurrentHashMap中的get()方法為什么可以不加鎖?5. javascript - QWebEngineView 如何爬 angular 的動態數據?6. html5 - 這個代碼顯示功能如何實現?7. javascript - 用JS 七牛上傳圖片出現文件已存在的錯誤(file exists)8. 工作近5年,3年Java Web ,近2年前端,未來何去何從?9. css3 - 圖片等比例縮放10. java - 字節流轉成字符串之后,在通過字符串轉成字節流后的文件為什么會不一樣?
