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 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的