如何使用Javascript/jQuery保存在浏览器(DOM)上修改的html

How to save html that was modified on the browser (the DOM) with Javascript/jQuery

本文关键字:DOM 修改 html 浏览器 Javascript 何使用 jQuery 存在 保存      更新时间:2023-09-26

首先让我澄清一下,我试图做的只是本地使用,用户可以直接访问html页面。

我尝试做的基本上是将文本附加并保存到HTML文件中。

这就是我所拥有的。

HTML(index.HTML)

<div id="receiver"></div>
<button id="insertButton">Insert</button>

JS-

$(document).ready( function() {
    $('#insertButton').click(function(){
        $('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');
    })
});

我不知道的是如何在追加后保存文件(index.html)。知道怎么做吗?这在Javascript或jQuery中可能吗?

您可以更改处理程序以执行以下操作:

$(document).ready( function() {
    $('#insertButton').click(function(){
        $('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');
        // Save the page's HTML to a file that is automatically downloaded.
        // We make a Blob that contains the data to download.
        var file = new window.Blob([document.documentElement.innerHTML], { type: "text/html" });
        var URL = window.webkitURL || window.URL;
        // This is the URL that will download the data.
        var downloadUrl = URL.createObjectURL(file);
        var a = document.createElement("a");
        // This sets the file name.
        a.download = "source.htm";
        a.href = downloadUrl;
        // Actually perform the download.
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    })
});

您应该在MDN上查看URL的兼容性矩阵和文档。值得注意的是,URL不适用于IE 9或更早版本。与Blob相同。

如果我理解正确,您需要在本地机器上使用它,以便临时使用,然后您可以将其存储在cookie中。因此,无论何时加载页面,都要检查cookie是否可用,如果可用,则从cookie中加载数据或加载新数据。除非cookie未被清除,否则您可以使用这些数据。

希望这能帮助。。。

不需要任何javascript。附加html后,只需按Ctrl+S即可使用修改后的html在本地保存文件。