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.cgvv.com.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. node.js - mysql如何通過knex查詢今天和七天內的匯總數據2. mysql 插入數值到特定的列一直失敗3. 360瀏覽器與IE瀏覽器有何區別???4. Python從URL中提取域名5. mysql - 百萬行的表中是否盡量避免使用update等sql語句?6. python - 在使用Pycharm時經常看到如下的樣式,小括號里紅色的部分是什么意思呢?7. javascript - 新浪微博網頁版的字數限制是怎么做的8. 怎么在網頁中設置圖片進行左右滑動9. javascript - 豆瓣的這個自適應是怎么做的?10. javascript - 用jsonp抓取qq音樂總是說回調函數沒有定義
