如何使用JavaScript替换整个HTML内容?

5
我尝试使用$("html").html(this.responseText);。这会替换内容,但不会替换head和body标签。
例如,如果我想替换此内容:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>...</script>
<script>...</script>
</head>
<body>

<h1>This is a Heading</h1>


<script>...</script>
</body>
</html>

然后我在检查器中检查了我的HTML结构,结果如下:

<!DOCTYPE html>
<html>
<title>Page Title</title>
<script>...</script>
<script>...</script>

<h1>This is a Heading</h1>

<script>...</script>

</html>

它搞乱了我的CSS。我尝试过不用脚本,效果很好。这个问题的解决方案是什么?

我还尝试了使用JavaScript的方法。

document.open();
document.write(this.responseText);
document.close(); 

但它会混淆我的JavaScript代码。我收到了重新声明语法错误。
我想实现的真实代码:
<script>
  
        var frm = $('#frm');
        var submitActors = frm.find('input[type=submit]');
        var submitActor = null;
        submitActors.click(function(event) {
                submitActor = this;  
        });
        
        frm.unbind('submit').submit(function () {
           
            var formAction = document.getElementById("frm").getAttribute('action'); // Get the form action.
            var data = "";
            var pageUrl = "";
            var test_uuid = "";
            var test_number = "";
            var qid = JSON.parse(sessionStorage.getItem('userChoice')).qid;
            
            
            
            if(submitActor.name == "cmdSave"){
                data = {
                    "cmdSave" : $("#cmdSave").val(),
                    "Answer": document.querySelector('input[name="Answer"]:checked').value,
                    "csrfmiddlewaretoken": document.querySelector('input[name=csrfmiddlewaretoken').value,
                    "qid": qid
                }
            }
            else if(submitActor.name == "cmdNext"){
                data = {
                    
                    "cmdNext": document.querySelector('#cmdNext').value,
                    "csrfmiddlewaretoken":document.querySelector('input[name=csrfmiddlewaretoken').value,
                    "qid": qid
                }
            }
            var httpRequest = new XMLHttpRequest();
            var formData = new FormData();
            
            
            
            Object.keys(data).forEach(function(key) {
                console.log(key, data[key]);
                formData.append(key, data[key]);
            });
                console.log(formData)
            httpRequest.onreadystatechange = function(){
                if ( this.readyState == 4 && this.status == 200 ) {
                var response = this.responseText;
                    console.log(this.responseText) // Display the result inside result element.

                    // 1.Option
                    {% comment %} document.open();
                    document.write(this.responseText);
                    document.close(); {% endcomment %}
                    
                    // 2.Option
                    
                    {% comment %} document.documentElement.innerHTML = this.responseText;  {% endcomment %}
                    
            
                    // 3.Option
                    $(document).ready(function(){
                        $("html").html(response);
                    });
                                                                             
                
                    test_number = document.getElementById("lblNrCrt").textContent;  
                    test_uuid = "{{test.uuid}}";
                    pageUrl = "/intro/" + test_uuid + "/" + test_number + "/";
                    window.history.pushState('', '', pageUrl);
                }
            };

            httpRequest.open("post", formAction);
            httpRequest.send(formData);

            return false;
        
        });

</script>


1
如果我执行 document.querySelector('html').innerText = 'yolo',它会替换所有内容。我不确定 jQuery 做了什么,但这将完成你所需的功能。 - Jeanluca Scaljeri
这是哪个浏览器? $("html").html("some text") 在我的Firefox中会抹掉所有的东西。另外,您确定this.responseText不恰巧包含那些标记吗? - VLAZ
响应文本包含那些标签,我已经检查过了。我正在使用Firefox。 - Arnold96
6个回答

11

就像我所指出的,它是可以完成的。

document.querySelector('html').innerText = 'yolo';

但是如果你需要呈现HTML,则应执行

document.querySelector('html').innerHTML = '<div>yolo</div>';

2
作为另一种选择,您可以获取 body 并转到其父级 document.body.parentElement。在这种方式下可能并没有什么好处,但是我偶尔发现找到子项并转到父项比尝试找到父项更有用。 - VLAZ
如果我发布两次,第二次我的JavaScript就无法运行。 - Arnold96
@Arnold96 这里有一个可行的例子:https://stackblitz.com/edit/typescript-3wubgf - Jeanluca Scaljeri

3
使用 Chrome 浏览器时,我发现响应(或任何您想用作新页面的 innerHTML)必须严格以 <head> 标签开头。而不是 <html> 或 <!DOCTYPE html> 或其他任何标签,否则替换innerHTML或使用document.write(response)将始终输出<body>...</body> 标签中的所有内容。
以下是我在本地使用的片段/页面,尝试了所有建议(均无效),直到我尝试将新页面内容/字符串压缩为 "<head>...</head><body>...</body>"。

document.querySelector("#replace-content-btn").addEventListener('click', function() {
  document.querySelector("html").innerHTML = `
    <head>
      <title>New Page Title</title>
    </head>
    <body>
      <p>New body content.<br>Inspect the head element!</p>
    </body>`;
});
<head>
  <title>Some Page Title</title>
</head>

<body>
  <p>Some body content.<br>Inspect the head element before and after button click.</p>
  <button type="button" id="replace-content-btn">Replace entire HTML</button>
</body>


请看我下面的回答:https://stackoverflow.com/a/77564316/2225546 - undefined

1

在您的字符串中查找标签内容:

function getByTag(tagname,htmlVal) { var tagHtmValue = $(htmlVal).find(tagname).html(); return tagHtmValue; }

用响应中的body和head替换头部和body内容:

$("head").html(getByTag("head",this.responseTex)); $("body").html(getByTag("body",this.responseTex));


1
JS: 使用 innerHTML 可以替换元素的所有 HTML 内容。
document.querySelector('html').innerHTML = '...'

Jquery:

$( document ).ready(function() {
  $('html').html('...');
});

0

我已经测试过以下代码是有效的!...

let responseTxt="<html> \
<head><title>changed hello</title></head><body><h1>Changed body</h1></body></html>"
$(document).ready(()=>{
 $(".action").click(()=>{
  $("html").html(responseTxt)
 });

});
<html>
<head><title>hello</title></head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
<h1>hello</h1>
<button class="action">Change HTML</button>
</body>
</html>


我尝试了这个解决方案,$(document).ready(()=>{...}) 解决了这个问题,但在我的实际项目中它不起作用...有什么可能导致它出错吗? - Arnold96
我更新了问题。所以我尝试将整个JavaScript代码放入就绪状态,但无论如何都没有起作用。 - Arnold96

0
回应Dima Pavlenko的帖子。这确实有效。

document.addEventListener("DOMContentLoaded", (e) => {
  document.querySelector("#replace-content-btn").addEventListener('click', function() {
    document.write(`
      <html>
        <head>
          <title>New Page Title</title>
        </head>
        <body>
          <p>New body content.<br>Inspect the head element!</p>
        </body>
      </html>`);
  });
});
<html>
  <head>
    <title>Some Page Title</title>
  </head>

  <body>
    <p>Some body content.<br>Inspect the head element before and after button click.</p>
    <button type="button" id="replace-content-btn">Replace entire HTML</button>
  </body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接