How to export source content within div to text/html file

前端 未结 4 1454
醉酒成梦
醉酒成梦 2020-12-03 03:44

Let\'s say I have

... Some html ...
and I need to take the html code within this div, place it inside a file and for
4条回答
  •  我在风中等你
    2020-12-03 04:17

    The intended can be achieved with a javascript method. The following function will let you add a personalized name with which you desire to download your text file.

    function saveTextAsFile()
    {
        //inputTextToSave--> the text area from which the text to save is
        //taken from
        var textToSave = document.getElementById("inputTextToSave").value;
        var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
        var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
        //inputFileNameToSaveAs-->The text field in which the user input for 
        //the desired file name is input into.
        var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
    
        var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "Download File";
        downloadLink.href = textToSaveAsURL;
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    
        downloadLink.click();
    }
    
    function destroyClickedElement(event)
    {
        document.body.removeChild(event.target);
    }
    

    The above was derived from here.

提交回复
热议问题