簡體   English   中英

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

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

首先讓我澄清一下,我正在嘗試做的只是本地使用,用戶可以直接訪問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的兼容性矩陣和文檔。 值得注意的是,IE 9或更早版本無法使用URL Blob

如果我理解正確,您需要在本地計算機上進行臨時使用,然后您可以將其存儲在cookie中。 因此,無論何時加載頁面,檢查cookie是否可用,如果是,則從cookie加載數據或加載新數據。 您可以使用此數據,除非並且直到cookie未被清除。

希望這可以幫助...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM