javascript 无法使用querySelector选择表单

o3imoua4  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(253)

我尝试使用querySelector在javascript中选择一个表单元素,但它不起作用,有时它会返回表单元素。
下面是我的代码:

JavaScript语言

const ele = document.querySelector('form');
console.log(ele);
ele.addEventListener('submit', function(e) {
    console.log("in the eventlister function");
    const pass = document.getElementsByClassName("P")[0].value;
    const cpass = document.getElementsByClassName("CP")[0].value; 
    const messagePara =document.getElementById("generated_message");
    if(pass != cpass){
        e.preventDefault();
        messagePara.textContent ="check your password!!";
                            messagePara.style.color= 'red';
                            return false;
    }
    else{
        messagePara.textContent ="";
    }
});

HTML

<form class="inputF">
                <div class="inputD">
                    <label for="fname" >Full Name</label>
                    <input type="text" id="fname" required>
                </div>
                <div class="inputD">
                    <label for="uname">Username</label>
                    <input type="text" id="uname">
                </div>
                <div class="inputD">
                    <label>Email address</label>
                    <input type="email" id="Email" placeholder="example@gmail.com" required >    
                </div>
                <div class="inputD">
                <label for="phn">Phone Number</label>
                    <input type="number" id="phn">
                </div>
                <div class="inputD">
                    <label for="pass">Password</label>
                    <div class="pass">
                        <input type="password"  class="P IptP" required>
                        <i class="fa fa-eye-slash show-hide"></i>
                    </div>
                </div>
                <div class="inputD">
                    <label for="cpass">Confirm Password</label>
                    <div class="pass">
                        <input type="password"  class="CP IptP" required>
                        <i class="fa fa-eye-slash show-hide"></i>
                    </div>
                </div>
                    <div>
                    <button id="save_btn" >Continue</button>
                   </div> 
                </form>

我尝试为窗体添加类并使用类名选择窗体,但仍然出现相同的问题。如何解决此问题?

6kkfgxo0

6kkfgxo01#

当在<header>中使用<script>操作DOM时,您需要等待文档加载完成。

document.body.addEventListener('load',function(){
  // Your DOM sensitive code here
});

否则,您可能希望在form标记后包含脚本

<!DOCTYPE html>
<html>
<!-- Your header; moving your script from here -->
<body>
<!-- Your form here -->
<!-- Move script here-->
<script>
// DOM sensitive code here as the last element in the body
</script>
</body>

相关问题