学习笔记

0131-DOM-文件-AJAX

Posted on 2022-02-01,5 min read

删除DOM
删除后子节点不在文档树中,但仍在内存中,可随时将其放到其他地方;

var willBeRemoved = document.getElementById(test-id);
var beRemovedParent = willBeRemoved.parentElement;
var removed = beRemovedParent.removeChild(willBeRemoved);
removed === willBeRemoved; //true;

ps:要注意,children属性是一个只读属性,删除多个节点时,要注意children属性时刻都在变化;

  • 练习删除Web开发不相关的节点
let prt = document.getElementById('test-list');
let removeArr = ['JavaScript','HTML','CSS'];
Array.from(prt.children).forEach(function(x){removeArr.includes(x.innerText)? x : prt.removeChild(x);});

[\S]查找非空白字符;

  • 注册信息验证练习:
<!-- HTML结构 -->
<form id="test-register" action="#" target="_blank" onsubmit="return checkRegisterForm()">
    <p id="test-error" style="color:red"></p>
    <p>
        用户名: <input type="text" id="username" name="username">
    </p>
    <p>
        口令: <input type="password" id="password" name="password">
    </p>
    <p>
        重复口令: <input type="password" id="password-2">
    </p>
    <p>
        <button type="submit">提交</button> <button type="reset">重置</button>
    </p>
</form>

<!-- JavaScript 内容 -->
<script>
var checkRegisterForm = function () {   
    let 
        usc = 0,
        psc = 0,
        in_us = document.getElementById('username'),
        in_ps = document.getElementById('password'),
        in_ps2 = document.getElementById('password-2');
    let 
        usexp = /[0-9a-zA-Z]{3,10}/,
        psexp = /[\S]{6,20}/;
    if(usexp.test(in_us.value)) {usc += 1;}
    if(!usexp.test(in_us.value)) {window.alert('用户名必须是3-10位英文字母或数字;'); return false;}
    if(psexp.test(in_ps.value)){psc += 1;}
    if(!psexp.test(in_ps.value)) {window.alert('口令必须是6-20位;'); return false;}
    if(in_ps.value!==in_ps2.value) {psc--; window.alert('两次口令必须一致;'); return false;}
    return usc&&psc; 
}
</script>

操作文件

  • 以预览图片为例
<form method="post" enctype="multipart/form-data">
    <p>图片预览:</p>
    <p></p>
    <div id="test-image-preview" style="border: 3px solid #ff0000; border-radius: 10px; width: 33%; height: 200px; background-size: contain; background-repeat: no-repeat; background-position: center center;">
    </div>
    <p></p>
    <p>
      <input type="file" id="test-image-file" name="test">
    </p>
    <p id="test-file-info">没有选择文件</p>
</form>

js代码及说明
FileReader()对象用来读取文件;
element.target.result将图片编码为base64数据;
preview.style.backgroundImage = 'url(' + data + ')';显示图片;

//确定js在HTML后加载
window.onload = function() {
var
    fileInput = document.getElementById('test-image-file'),
    info = document.getElementById('test-file-info'),
    preview = document.getElementById('test-image-preview');
// 监听change事件:
fileInput.addEventListener("change", previewFunc);
function previewFunc () {
    // 清除背景图片:
    preview.style.backgroundImage = '';
    // 检查文件是否选择:
    if (!fileInput.value) {
        info.innerHTML = '没有选择文件';
        return;
    }
    // 获取File引用:
    var file = fileInput.files[0];
    // 获取File信息:
    info.innerHTML = '文件: ' + file.name + '<br>' +
                     '大小: ' + file.size + '<br>' +
                     '修改: ' + file.lastModified;
    if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        alert('不是有效的图片文件!');
        return;
    }
    // 读取文件:
    var reader = new FileReader();
    reader.onload = function(e) {
        var data = e.target.result; // 'data:image/jpeg;base64,/9j/4AAQSk...(base64编码)...'            
        preview.style.backgroundImage = 'url(' + data + ')';
        console.log(data);
    };
    // 以DataURL的形式读取文件:
    reader.readAsDataURL(file);
}
} //确定js在HTML后加载

AJAX入门

var xhttp = new XMLHttpRequest();创建xhttp为名的XMLHttpRequest的对象;
xhttp.onreadystatechange = function() { ... }XMLHttpRequest的状态改变时回调函数;
xmlhttp.readyState

  • 0: 请求未初始化
  • 1: 服务器连接已建立
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已就绪

xmlhttp.status

  • 200: "OK"
  • 404: 未找到页面
xmlhttp.open("GET","/try/ajax/gethint.php?q="+str,true);
xmlhttp.send();

open(method,url,async)使readyState改变:

method:请求的类型;GET 或 POST,大小写均可;


下一篇: 0130-继承-DOM-HTML排序→

loading...