用于使用javascript保存div内容的HTML按钮

时间:2015-04-17 14:58:34

标签: javascript html file button save

我需要使用纯javascript保存div的内容。 我只是编辑了一个小提琴,但我无法使其奏效:(

jsfiddle

<div id="content">
<h1>Hello world</h1>
<i>Hi everybody</i>

下载

function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content");
}

4 个答案:

答案 0 :(得分:2)

关闭,你需要innerHTML&amp;触发点击:

function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML; // Grab the HTML
    a.click(); // Trigger a click on the element
}

Working Fiddle

答案 1 :(得分:2)

在您的jsfiddle中,Java脚本配置为 onLoad ,这就是为什么不调用 download()的原因。将其更改为 No-Wrap ,然后您就可以在按钮的 onClick 上调用 download()

将下载()更新为

function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML;
     a.click();

}

答案 2 :(得分:0)

在jsfiddle中,你不能在html事件中运行javascript函数(比如onClick),除非javascript包含在标签中。(没关系)

试试这个:

HTML

<div id="content">
    <h1>Hello world</h1>
    <i>Hi everybody</i>
</div>
<button id="download">Download</button>

JS

var download_button = document.getElementById('download');
download_button.onclick = download;

function download(){
    var content = document.getElementById('content')
    console.log(content);
}

updated jsfiddle

答案 3 :(得分:0)

我同意RGraham。但是,如果您使用jQuery,则可以这样做。

<div id="content">
    <h1>Hello world</h1>
    <i>Hi everybody</i>
</div>
<button class="download">Download</button>

<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $('.download').on('click', function(){
       $('<a />').attr({
              download: 'export.html', 
              href: "data:text/html," + $('#content').html() 
       })[0].click()
    });
</script>