[英]How can i download some of content instead of all content of web page when i click on Save as HTML in browser
When I click on save as HTML button its Download all content of web page but i have require to Download some for specific content from all content.当我单击另存为 HTML 按钮时,它会下载 web 页面的所有内容,但我需要从所有内容中下载一些特定内容。
function download(filename, contents) { const anchor = document.createElement('a'); anchor.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents)); anchor.setAttribute('download', filename); anchor.style.display = 'none'; document.body.appendChild(anchor); anchor.click(); document.body.removeChild(anchor); } const btn = document.querySelector('#save-btn'); btn.addEventListener('click', (evt) => { const container = document.createElement('div'); const html = document.createElement('html'); html.innerHTML = document.documentElement.innerHTML; container.appendChild(html); download('index.html', container.innerHTML); });
<p>Hello World</p> <button id="save-btn">Save as HTML</button> <div> <p>Hello World-1</p> <p>Hello World-2</p> <p>Hello World-3</p> </div>
On above HTML Example, when i click on save as HTML Button i have download some of portion of file like download div content instead of all content.在上面的 HTML 示例中,当我单击另存为 HTML 按钮时,我下载了部分文件,例如下载 div 内容而不是所有内容。 in sort when I open download file it display only this content:
当我打开下载文件时,它只显示以下内容:
<div>
<p>Hello World-1</p>
<p>Hello World-2</p>
<p>Hello World-3</p>
</div>
To only download the HTML of a specific element, change the logic to select that element instead of the entire body, like this:要仅下载特定元素的 HTML,请将逻辑更改为该元素而不是整个主体的 select,如下所示:
document.querySelector('#save-btn').addEventListener('click', e => {
e.preventDefault();
let html = document.querySelector('div').outerHTML; // update this selector in your local version
download('index.html', html);
});
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.