搜尋

首頁  >  問答  >  主體

javascript - 為什麼無法實現表單原件失去焦點後改變提示的樣式?

要實現一個表單,在輸入密碼一欄中如果沒有輸入或兩次輸入不一致則顯示提示,否則隱藏。但提示始終出不來,求助又是為什麼呢?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<code><!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="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";

    else

        obj.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)" id="pwd"/>

        <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>

</code>

css程式碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

<code>@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{}</code>

曾经蜡笔没有小新曾经蜡笔没有小新2875 天前571

全部回覆(1)我來回復

  • 仅有的幸福

    仅有的幸福2017-05-16 13:40:30

    找到你程式碼中如下這段

    1

    2

    3

    4

    <code>        <p><input type="password" onblur="checkEmpty(this)" id="pwd"/>

            <span style="display:none">密码不能为空!</span></p>

            <p><input type="password" onblur="checkPwd(this)"/>

            <span style="display:none">密码不一致!</span></p></code>

    請刪除 之間的換行即可。

    原因
    DOMElement.nextSibling屬性回傳該節點下一個同級DOM元素,換行或空格都算做一個#text類型的節點。之前你的程式碼nextSibling回傳的一個文字節點,在其上設定style屬性,當然不能達成你的需求。

    如果不信,你還可以驗證一下:不要改變你的html程式碼,把腳本中 DOMElement.nextSibling換成 DOMElement.nextSibling.nextSibling 也能正常運作。

    回覆
    0
  • 取消回覆