js中null和 document.getElementById("userId")小结

本文介绍了解决IE8中无法通过getElementById获取元素值的问题,并提供了360浏览器中确保正确获取DOM元素的方法。同时,文中还讨论了如何判断变量是否为null的几种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1、IE8中, document.getElementById("userId").value; 

       获得不了对象值,把函数写在变量声明后面即可。

       顺序如下:

       <body>

            <input type="text" name="userId" id="userId"  tabindex="3"/>

       

              <script type="text/javascript">
                       function checkInput() {

                               var userId = document.getElementById("userId");   

                      }

               </script >

        </body>

         此时,可以获得其值,如果是放在<head></head>之间,取不到。

2、null的判断

          var userId = document.getElementById("userId");   

         var isNull=(!userId && typeof userId != "undefined" && userId != 0);

                     typeof exp != "undefined" 排除了 undefined; exp != 0 排除了数字零,!exp排除 false。

3、360浏览器中,   

    3.1 如下将获得null,虽然在IE中正常,但在360中由于变量没有ID值,故会是null.

        <input type="text" name="userId"  tabindex="3"/>

        var userId = document.getElementById("userId");   //null

         3.2 加上ID后,可以获得。

      <input type="text" name="userId"    id="userId"    tabindex="3"/>  

        var userId = document.getElementById("userId");   //不再是null



<!DOCTYPE html> <html> <head> <title>个人信息管理</title> </head> <body> <h1>个人信息管理</h1> <div> <h2>添加用户</h2> <form id="user-form"> <label for="name">姓名:</label> <input type="text" id="name" name="name" required> <label for="email">邮箱:</label> <input type="email" id="email" name="email" required> <button type="submit">添加用户</button> </form> </div> <div id="user-list"></div> <script> // 获取所有用户 function fetchUsers() { fetch('/api/users') .then(response => response.json()) .then(data => { const userList = document.getElementById('user-list'); userList.innerHTML = ''; if (data.length === 0) { userList.innerHTML = '<p>没有用户数据</p>'; } else { data.forEach(user => { const userDiv = document.createElement('div'); userDiv.innerHTML = `${user.name} (${user.email}) <button class="edit-btn" data-id="${user.id}">编辑</button> <button class="delete-btn" data-id="${user.id}">删除</button>`; userList.appendChild(userDiv); }); // 为所有删除按钮添加点击事件监听器 document.querySelectorAll('.delete-btn').forEach(button => { button.addEventListener('click', function() { const userId = this.getAttribute('data-id'); deleteUser(userId); }); }); // 为所有编辑按钮添加点击事件监听器 document.querySelectorAll('.edit-btn').forEach(button => { button.addEventListener('click', function() { const userId = this.getAttribute('data-id'); editUser(userId); }); }); } }) .catch(error => { console.error('获取用户数据时出错:', error); const userList = document.getElementById('user-list'); userList.innerHTML = '<p>获取用户数据时出错</p>'; }); } // 页面加载时获取用户数据 window.onload = fetchUsers; // 添加用户 document.getElementById('user-form').addEventListener('submit', function(event) { event.preventDefault(); const name = document.getElementById('name').value; const email = document.getElementById('email').value; fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, email }), }) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { alert('用户添加成功'); fetchUsers(); }) .catch(error => { console.error('添加用户时出错:', error); alert('添加用户时出错'); }); }); // 删除用户 function deleteUser(userId) { if (confirm('确定要删除这个用户吗?')) { fetch(`/api/users/${userId}`, { method: 'DELETE', }) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { alert('用户删除成功'); fetchUsers(); }) .catch(error => { console.error('删除用户时出错:', error); alert('删除用户时出错'); }); } } // 编辑用户 function editUser(userId) { const newName = prompt('请输入新的姓名:', ''); const newEmail = prompt('请输入新的邮箱:', ''); if (newName !== null && newEmail !== null) { fetch(`/api/users/${userId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: newName, email: newEmail }), }) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { alert('用户更新成功'); fetchUsers(); }) .catch(error => { console.error('更新用户时出错:', error); alert('更新用户时出错'); }); } } </script> </body> </html> from flask import Blueprint, request, jsonify from models import db, User api = Blueprint('api', __name__) @api.route('/users', methods=['GET']) def get_users(): users = User.query.all() return jsonify([user.to_dict() for user in users]) @api.route('/users', methods=['POST']) def create_user(): data = request.json user = User(name=data['name'], email=data['email']) db.session.add(user) db.session.commit() return jsonify(user.to_dict()), 201 @api.route('/users/<int:user_id>', methods=['PUT']) def update_user(user_id): user = User.query.get_or_404(user_id) data = request.json user.name = data.get('name', user.name) user.email = data.get('email', user.email) db.session.commit() return jsonify(user.to_dict()) @api.route('/users/<int:user_id>', methods=['DELETE']) def delete_user(user_id): user = User.query.get_or_404(user_id) db.session.delete(user) db.session.commit() return '', 204 修改代码实现删除用户
05-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值