同一函数中的多个 DOM 更新

multiple dom updates in the same function

本文关键字:DOM 更新 函数      更新时间:2023-09-26

我有一个JavaScript函数,从其中包含的指令的开始到结束,需要一些时间才能执行。在执行过程中,我想显示一个div 元素,然后在执行后我想隐藏它。我写了这个简单的代码片段,但不起作用:

<div style="height: 100px; width: 100px; background-color: red; display: none;" id="d"></div>
<script>
    document.getElementById('d').style.display='block';
    console.log('start');
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","http://www.google.com",false);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    try{
        xmlhttp.send();
    } catch (e) {
    }
    var response = xmlhttp.responseText
    document.getElementById('d').style.display='none';
    console.log('finish');
</script>

如果您查看控制台,您会发现"开始"和"完成"语句之间有一个间隔,但div 保持隐藏状态!这怎么可能以及如何解决?

如果你想用jQuery(http://jquery.com/让你的生活变得简单执行以下操作:1. 将 jQuery 包含在您的页面中2. 执行以下操作:

<div style="height: 100px; width: 100px; background-color: red; display: none;" id="d"></div>
<script>
    $("#d").show();
    $.ajax({
        type:'POST',
        url:'http://www.google.com',
        success: function(data) {
        //code on successful response
        },
        error: function(xhr) {
        // code on error response
        },
        complete:function(){
         // code on  - success/failure
         $("#d").hide();
        }
    });
</script>

享受