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

时间:2014-11-01 13:41:52

标签: javascript jquery html

首先让我澄清一点,我尝试做的只是本地使用,用户可以直接访问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吗?

3 个答案:

答案 0 :(得分:3)

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

$(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的兼容性矩阵和文档。值得注意的是,{9}或更早版本无法使用URLBlob也是如此。

答案 1 :(得分:0)

如果我理解正确,您需要在本地计算机上进行临时使用,然后您可以将其存储在cookie中。 因此,无论何时加载页面,检查cookie是否可用,如果是,则从cookie加载数据或加载新数据。 您可以使用此数据,除非并且直到cookie未被清除。

希望这会有所帮助......

答案 2 :(得分:-1)

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