javascript - 為什么無法實(shí)現(xiàn)表單原件失去焦點(diǎn)后改變提示的樣式?
問題描述
要實(shí)現(xiàn)一個(gè)表單,在輸入密碼一欄中如果沒有輸入或兩次輸入不一致則顯示提示,否則隱藏。但是提示始終出不來,求助是為什么呢?
<!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.leifengta.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>用戶登錄驗(yàn)證</title></head><body><form class='bg'> <ul><li>用戶名:</li><li>輸入密碼:</li><li>確認(rèn)密碼:</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>
請(qǐng)刪掉 <input/>和<span>之間的換行即可。
原因DOMElement.nextSibling屬性返回該節(jié)點(diǎn)下一個(gè)同級(jí)DOM元素,換行或者空格都算做一個(gè)#text類型的節(jié)點(diǎn)。之前你的代碼nextSibling返回的一個(gè)文本節(jié)點(diǎn),在其上設(shè)置style屬性,當(dāng)然不能達(dá)成你的需求。
如果不信,你還可以驗(yàn)證一下:不改變你的html代碼,把腳本中 DOMElement.nextSibling換成 DOMElement.nextSibling.nextSibling 也能正常工作。
相關(guān)文章:
1. 運(yùn)行python程序時(shí)出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯(cuò)誤?2. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境3. 利用IPMI遠(yuǎn)程安裝centos報(bào)錯(cuò)!4. spring-mvc - spring-session-redis HttpSessionListener失效5. javascript - QQ第三方登錄的問題6. 測(cè)試自動(dòng)化html元素選擇器元素ID或DataAttribute [關(guān)閉]7. javascript - node得到req不能得到boolean8. javascript - 最近用echarts做統(tǒng)計(jì)圖時(shí)遇到兩個(gè)問題!!9. java - Spring boot 讀取 放在 jar 包外的,log4j 配置文件,系統(tǒng)有創(chuàng)建日志文件,不寫入日志信息。10. javascript - 在 model里定義的 引用表模型時(shí),model為undefined。

網(wǎng)公網(wǎng)安備