Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript将html页面内容保存在.txt文件中?_Javascript_Jquery_Html_Css - Fatal编程技术网

如何使用JavaScript将html页面内容保存在.txt文件中?

如何使用JavaScript将html页面内容保存在.txt文件中?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我已经为测验创建了一个静态html页面。 下面是我的代码 <style> body { font-family: Open Sans; } #quiz {display:none;} #prev {display:none;} #start {display:none;} #submit{display:none;} ul{list-style:outside none none; margin:0px; padding:0px;} .question>div>d

我已经为测验创建了一个静态html页面。 下面是我的代码

<style>
    body {
font-family: Open Sans;
}
#quiz {display:none;}
#prev {display:none;}
#start {display:none;}
#submit{display:none;}
ul{list-style:outside none none; margin:0px; padding:0px;}
.question>div>div>div>p{    color: #fff;
background-color: #337ab7;
padding: 6px;
border-radius: 3px;}
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;}
</style>
<body>
<div class='container question'>
    <div class='row'>
        <div class='col col-md-12' id='quiz'>
        </div>
    </div>
</div>

<div class='container question' >
<div class='row' id='quiz'>
</div>
</div>
<br/>
<div class='container'>
            <a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a>
            <a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a> 
            <a href='#' class='btn btn-md btn-default' id='start'>Start Over</a>


        <div class='button' id='submit' style='display:none;'>
            <input type='text' placeholder='Name' id="inputFileNameToSaveAs"/>
            <button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button>
        </div>
</div>

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>

    <script type="text/javascript">


    function saveTextAsFile()
    {
    var textToSave = document.getElementById("question").text;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    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);
    }

    function loadFileAsText()
    {
        var fileToLoad = document.getElementById("fileToLoad").files[0];

        var fileReader = new FileReader();
        fileReader.onload = function(fileLoadedEvent) 
        {
            var textFromFileLoaded = fileLoadedEvent.target.result;
            document.getElementById("inputTextToSave").value = textFromFileLoaded;
        };
        fileReader.readAsText(fileToLoad, "UTF-8");
    }

                (function() {
      var questions = [
      {
        question: "Which one is correct?",
        choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'],
        correctAnswer: 0
      },

      ];

      var questionCounter = 0; //Tracks question number
      var selections = []; //Array containing user choices
      var quiz = $('#quiz'); //Quiz div object

      // Display initial question
      displayNext();

      // Click handler for the 'next' button
      $('#next').on('click', function (e) {
        e.preventDefault();

        // Suspend click listener during fade animation
        if(quiz.is(':animated')) {        
          return false;
        }
        choose();

        // If no user selection, progress is stopped
        if (isNaN(selections[questionCounter])) {
          alert('Please make a selection!');
        } else {
          questionCounter++;
          displayNext();
        }
      });

      // Click handler for the 'prev' button
      $('#prev').on('click', function (e) {
        e.preventDefault();

        if(quiz.is(':animated')) {
          return false;
        }
        choose();
        questionCounter--;
        displayNext();
      });

      // Click handler for the 'Start Over' button
      $('#start').on('click', function (e) {
        e.preventDefault();

        if(quiz.is(':animated')) {
          return false;
        }
        questionCounter = 0;
        selections = [];
        displayNext();
        $('#start').hide();
      });

      // Animates buttons on hover
      $('.button').on('mouseenter', function () {
        $(this).addClass('active');
      });
      $('.button').on('mouseleave', function () {
        $(this).removeClass('active');
      });

      // Creates and returns the div that contains the questions and 
      // the answer selections
      function createQuestionElement(index) {
        var qElement = $('<div>', {
          id: 'question'
        });

        var header = $('<p>Question ' + (index + 1)  + '</p>');
        qElement.append(header);

        var question = $('<h3>').append(questions[index].question);
        qElement.append(question);

        var radioButtons = createRadios(index);
        qElement.append(radioButtons);

        return qElement;
      }

      // Creates a list of the answer choices as radio inputs
      function createRadios(index) {
        var radioList = $('<ul>');
        var item;
        var input = '';
        for (var i = 0; i < questions[index].choices.length; i++) {
          item = $('<li>');
          input = '<input type="radio" name="answer" value=' + i + ' />';
          input += questions[index].choices[i];
          item.append(input);
          radioList.append(item);
        }
        return radioList;
      }

      // Reads the user selection and pushes the value to an array
      function choose() {
        selections[questionCounter] = +$('input[name="answer"]:checked').val();
      }

      // Displays next requested element
      function displayNext() {
        quiz.fadeOut(function() {
          $('#question').remove();

          if(questionCounter < questions.length){
            var nextQuestion = createQuestionElement(questionCounter);
            quiz.append(nextQuestion).fadeIn();
            if (!(isNaN(selections[questionCounter]))) {
              $('input[value='+selections[questionCounter]+']').prop('checked', true);
            }

            // Controls display of 'prev' button
            if(questionCounter === 1){
              $('#prev').show();
            } else if(questionCounter === 0){

              $('#prev').hide();
              $('#next').show();
            }
          }else {
            var scoreElem = displayScore();
            quiz.append(scoreElem).fadeIn();
            $('#next').hide();
            $('#prev').hide();
            $('#start').show();
            $('#submit').show();
          }
        });
      }

      // Computes score and returns a paragraph element to be displayed
      function displayScore() {
        var score = $('<h4>',{id: 'question'});

        var numCorrect = 0;
        for (var i = 0; i < selections.length; i++) {
          if (selections[i] === questions[i].correctAnswer) {
            numCorrect++;
          }
        }

        score.append('You got ' + numCorrect + ' questions out of ' +
                     questions.length + ' right!!!');
        return score;
      }
    })();


    </script>
        </body>

身体{
字体系列:开放式SAN;
}
#测验{显示:无;}
#上一个{显示:无;}
#开始{显示:无;}
#提交{显示:无;}
ul{列表样式:外部无;边距:0px;填充:0px;}
.question>div>div>p{color:#fff;
背景色:#337ab7;
填充:6px;
边界半径:3px;}
.navbar默认值{背景颜色:#fff;边框颜色:#ddd;边框半径:0px;}

提交 函数saveTextAsFile() { var textToSave=document.getElementById(“问题”).text; var textToSaveAsBlob=新Blob([textToSave],{type:“text/plain”}); var textToSaveAsURL=window.URL.createObjectURL(textToSaveAsBlob); var fileNameToSaveAs=document.getElementById(“inputFileNameToSaveAs”).value; var downloadLink=document.createElement(“a”); downloadLink.download=fileNameToSaveAs; downloadLink.innerHTML=“下载文件”; downloadLink.href=textToSaveAsURL; downloadLink.onclick=destroyClickedElement; downloadLink.style.display=“无”; document.body.appendChild(下载链接); downloadLink.click(); } 函数销毁ClickedElement(事件) { document.body.removeChild(event.target); } 函数loadFileAsText() { var fileToLoad=document.getElementById(“fileToLoad”).files[0]; var fileReader=newfilereader(); fileReader.onload=函数(fileLoadedEvent) { var textFromFileLoaded=fileloadevent.target.result; document.getElementById(“inputTextToSave”).value=textFromFileLoaded; }; readAsText(fileToLoad,“UTF-8”); } (功能(){ 变量问题=[ { 问题:“哪一个是正确的?”, 选项:['a!=b','a=!b','a:=b','a=-b'], 正确答案:0 }, ]; var questionCounter=0;//跟踪问题编号 var selections=[];//包含用户选择的数组 var quick=$('#quick');//quick div对象 //显示初始问题 displayNext(); //单击“下一步”按钮的处理程序 $(“#下一步”)。在('click',函数(e){ e、 预防默认值(); //在淡入淡出动画期间暂停单击侦听器 如果(quick.is(':animated'){ 返回false; } 选择(); //如果没有用户选择,则停止进度 if(isNaN(选择[问询计数器]){ 警报('请选择!'); }否则{ 问句器++; displayNext(); } }); //单击“prev”按钮的处理程序 $('prev')。在('click',函数(e)上{ e、 预防默认值(); if(quick.is(':animated')){ 返回false; } 选择(); 问讯台--; displayNext(); }); //单击“重新开始”按钮的处理程序 $('#start')。在('click',函数(e)上{ e、 预防默认值(); if(quick.is(':animated')){ 返回false; } 问讯员=0; 选择=[]; displayNext(); $('#start').hide(); }); //设置悬停按钮的动画 $('.button')。在('mouseenter',函数(){ $(this.addClass('active'); }); $('.button')。打开('mouseleave',函数(){ $(this.removeClass('active'); }); //创建并返回包含问题和答案的div //答案选择 函数createQuestionElement(索引){ 变量qElement=$(''{ id:“问题” }); var头=$(“问题”+(索引+1)+”

); 追加(标题); 变量问题=$('').append(问题[index].question); 附加(问题); var radioButtons=createRadios(索引); qElement.append(单选按钮); 返回元素; } //创建答案选项列表作为无线电输入 函数createRadios(索引){ var放射科医生=$(“
    ”); var项目; var输入=“”; 对于(var i=0;i”); 输入=''; 输入+=问题[索引]。选项[i]; 项目。追加(输入); 放射科医生。追加(项目); } 返回放射科医生; } //读取用户选择并将值推送到数组 函数选择(){ 选择[questionCounter]=+$('input[name=“answer”]:选中')。val(); } //显示下一个请求的元素 函数displayNext(){ 测验.淡出(函数(){ $(“#问题”).remove(); if(问询台function downloadFile(filename, content) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); }