douya7121 2017-02-25 15:28
浏览 53
已采纳

document.getElementById(“...”)。innerHTML不会更改h2标记

After document.getElementsById("occ").innerHTML = "Already registered"; tag <h2 style="color: red" id ="occ"></h2> doesn't change, but page looks like it reloaded. Code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ustory - Register</title>

<link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<link href="CSS_defaults.css" rel="stylesheet">
<script src="Ustory_JS.js"></script>
</head>

<body>

<?php
    if($_GET['occupied'] == "true") {
        echo($_GET['occupied']);
        $occupied = "true";
    }
?>

<script>
    var occ = <?php echo json_encode($occupied); ?>;
    alert(typeof(occ));
    if(occ == "true") {
        alert("done");
        document.getElementsById("occ").innerHTML = "Already registered";
    }
</script>

<div id="reg_in" class="reg" style="color:#FF4D50;">
  <form class="reg" name="register" action="U_story_reg.php" method="post" onsubmit="return register_()">
    <input type="text" name="firstname" id="firstname" placeholder="Meno" required> <b>*</b><br>
    <input type="text" name="lastname" id="lastname" placeholder="Priezvisko" required> <b>*</b><br>
    <input type="text" name="nick" id="nick" placeholder="Prezívka">&nbsp;&nbsp;&nbsp;<br>
    <input type="email" name="mail" id="mail" placeholder="E-mail" required> <b>*</b><br>
    <input type="password" name="pass" id="pass" placeholder="Heslo" required> <b>*</b><br>
    <input type="password" name="pass_again" id="pass_again" placeholder="Heslo znovu" required> <b>*</b><br>
    <input type="submit" value="Submit">
        <h2 style="color: red" id ="occ"></h2>
  </form>
</div>
<h2 style="color: red" id ="occ"></h2>
</body>
</html>

Do you have any idea why document.getElementsById("occ").innerHTML = "Already registered"; doesn't work ?

  • 写回答

2条回答 默认 最新

  • douwen1549 2017-02-25 15:31
    关注

    The code is executing before the DOM element has loaded & you have a typo in getElementsById should be getElementById. You have to either move the code below the html element you are trying to change or wrap it in a $(document).ready function. Like this:

    $(document).ready(function() {
        var occ = <?php echo json_encode($occupied); ?>;
        alert(typeof(occ));
        if(occ == "true") {
            alert("done");
            document.getElementById("occ").innerHTML = "Already registered";
        }
     });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)