单击按钮时如何克隆html页面

时间:2020-06-04 09:23:26

标签: html clone atag

当我单击

时,如何在新的_blank页中克隆html

btn_change_folder_style_seg

btn_change_folder_style_raw

然后内容将是

<img src="./pic/web_show/3_seg/01.jpg" alt="">
<img src="./pic/web_show/3_seg/02.jpg" alt="">

<img src="./pic/web_show/3_raw/01.jpg" alt="">
<img src="./pic/web_show/3_raw/02.jpg" alt="">

现在完整的代码

<img src="./pic/web_show/3/01.jpg" alt="">
<img src="./pic/web_show/3/02.jpg" alt="">
<img src="./pic/web_show/3/03.jpg" alt="">

<input type="button" id="btn_change_folder_style_seg" value="style seg"></input>
<input type="button" id="btn_change_folder_style_raw" value="style raw"></input>

<script>
    $(function() {
        $('#btn_change_folder_style_seg').click(function() {
            alert("style_seg")
            var imagePath = $('img');
            imagePath.attr('src', function(index, attr) {
            if (attr) {
                return attr.replace('3/', index + 1 + '_seg/');
            }
            });
        });
        $('#btn_change_folder_style_raw').click(function() {
            alert("style_raw")
            var imagePath = $('img');
            imagePath.attr('src', function(index, attr) {
            if (attr) {
                return attr.replace('3/', index + 1 + '_raw/');
            }
            });
        });
    })
</script>

1 个答案:

答案 0 :(得分:0)

首先,您需要选择HTML标记,然后通过cloneNode(true)方法对其进行复制,必须添加true才能复制其子标记

然后,您可以根据需要编辑克隆的HTML(删除Elm-编辑elm等)

因此,您必须通过(.outerHTML)将其转换为字符串

之后,您必须创建一个新的Blob对象实例,并在其中添加字符串化的内容并添加文件类型

const file = new Blob([content],{type:'text / html'});

然后,您将需要锚标记来创建HTML文件的下载链接

a.href = URL.createObjectURL(file);

然后,如果您单击按钮标记,则触发要单击的锚标记

这就是我希望该摘要进一步阐明我的答案

// select button
const btn = document.getElementById('btn');

// add click event
btn.addEventListener('click', () => {
    // Select anchor
    const a = document.getElementById('a');

    // select html tag
    const html = document.querySelector('html');
    // clone html
    const clonedHtml = html.cloneNode(true);

    // select elements
    const body = clonedHtml.querySelector('body');
    // wipe out body
    body.innerHTML = '';

    // create div
    const div = document.createElement('div');
    // add text
    div.innerText = 'new div';
    // append div
    body.append(div);

    //* append to content
    let content = `<!DOCTYPE html>`;
    content += clonedHtml.outerHTML;
    console.log(content);

    // create HTML file
    let file = new Blob([content], {
        type: 'text/html'
    });

    // add href link
    a.href = URL.createObjectURL(file);
    // name file
    a.download = 'New.html';
    // run click
    a.click();

});
<div class="div1">1</div>
<div class="div2">2</div>

<button type="button" id="btn">Generate HTML file</button>
<a id="a" href="" style="display: none;"></a>