javascript
JavaScript——易班优课YOOC课群在线测试自动答题解决方案(十五)整合升级+引入jQuery
前文
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(一)答案獲取
Spring Boot——易班優課YOOC課群在線測試自動答題解決方案(二)答案儲存
Spring Boot——易班優課YOOC課群在線測試自動答題解決方案(三)答案查詢
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(四)答案顯示
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(五)簡單腳本
Spring Boot——易班優課YOOC課群在線測試自動答題解決方案(六)后端改造
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(七)隨機答案
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(八)功能面板
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(九)ID標簽
Vue + Element UI + Spring Boot——易班優課YOOC課群在線測試自動答題解決方案(十)問題管理頁面
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(十一)恢復右鍵、選擇和復制
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(十二)腳本整合
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(十三)自動答題
JavaScript——易班優課YOOC課群在線測試自動答題解決方案(十四)自動刷題
基本概念
?jQuery:?jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之后又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝JavaScript常用的功能代碼,提供一種簡便的JavaScript設計模式,優化HTML文檔操作、事件處理、動畫設計和Ajax交互。
問題描述
1、腳本分離,不利于管理;
2、XMLHttpResquest方式繁瑣;
3、不能滿足一些DOM操作
問題分析?
如果對腳本整合,需要判斷URL,并且易班課群采用部分刷新,雖然URL會發生改變,但是無法觸發腳本,需要監控URL變化。
解決方案
注:完成從XMLHttpResquest到jQuery AJAX的重構,但只對部分DOM操作做了jQuery重構?
已完成對之前所有方案的整合。
此腳本已經是完整方案。?
// ==UserScript== // @name 易班優課YOOC浙理助手 // @namespace http://tampermonkey.net/ // @version 0.1 // @description 浙江理工大學易班優課YOOC測試、刷題 // @author STZG // @match *://*.yooc.me/* // @grant unsafeWindow // @grant GM_xmlhttpRequest // @grant GM_setClipboard // @require https://code.jquery.com/jquery-3.5.1.js#sha256=QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc= // @updateURL https://localost/MyZSTU/js/yooc/yooc_helper.js // @license MIT // ==/UserScript==(function() {// 設置修改后,需要刷新或重新打開網課頁面才會生效var setting = {},_self = unsafeWindow,top = _self,url;var $ = _self.jQuery || top.jQuery,parent = _self == top ? self : _self.parent,Ext = _self.Ext || parent.Ext || {},UE = _self.UE,vjs = _self.videojs;var ajaxUsualErrorMessage=(e)=>{if(e.status==500){//頁面函數xAlert('失敗','網絡請求失敗')}else if(e.status==404){//頁面函數xAlert('失敗','找不到網頁')}}var analysisDetailAnswerPage=(pagehtml)=>{console.log(pagehtml);//創建DOMvar pageDOM=document.createElement("html");pageDOM.innerHTML=pagehtmlvar page=$(pageDOM)console.log(page)//獲取考試信息var groupData=page.find('#group-data')var groupId=groupData.attr("data-group-id")var examId=groupData.attr("data-exam-id")//獲取問題信息var question=page.find('.question-board')console.log(question)//數據封裝var question_arr=[]question.each((index,q)=>{question_arr.push({id:q.id,question:q.outerHTML.replace(/the-ans fls/g,"the-ans crt").replace(/<li class="crt"/g,'<li class=""').replace(/<li class="fls"/g,'<li class=""')})let aq=$("#"+q.id).find('.the-ans')if(aq.length==1){aq.html($(q).find('.the-ans').html())}})return {group:groupId,exam:examId,questions:question_arr}}var getDetailPage=(groupId,examId)=>{return $.ajax({//請求方式type : "GET",//請求地址url :'https://www.yooc.me/group/'+groupId+'/exam/'+examId+'/detail'});}var uploadAnswer=(groupId,examId,question_arr)=>{return $.ajax({//請求方式type : "POST",//請求的媒體類型contentType: "application/json;charset=UTF-8",//請求地址url : "https://localost/MyZSTU/yooc/group/"+groupId+"/exam/"+examId+"/upload",//數據,json字符串data : JSON.stringify(question_arr)});}var getAnswer=(groupId,examId,question_arr)=>{return $.ajax({//請求方式type : "GET",//請求地址url : "https://localost/MyZSTU/yooc/group/"+groupId+"/exam/"+examId+"/answer?question="+question_arr,});}var unblock=()=>{//選擇document.onselectstart= function(e){e = e || window.event;e.returnValue = true;return true;}//鼠標按下document.onmousedown = function(e) {e = e || window.event;e.returnValue = true;return true;}//鼠標右鍵菜單document.oncontextmenu = function(e) {e = e || window.event;e.returnValue = true;return true;}window.onkeydown = function(e) {//Ctrl+S 保存if (e.ctrlKey && e.keyCode == 83) {e.returnValue = true;return true;}//Ctrl+P 打印if (e.ctrlKey && e.keyCode == 80) {e.returnValue = true;return true;}//Ctrl+C 復制if (e.ctrlKey && e.keyCode == 67) {e.returnValue = true;return true;}}}var examsPage=()=>{//獲取考試信息var group=document.getElementById('group-data')var groupId=group.getAttribute("data-group-id")var csrf=group.getAttribute("data-csrf")var auth=group.getAttribute("data-auth")var seeExam=(exam)=>{let a_score=exam.getElementsByClassName('score')[0]if(a_score&&a_score.innerHTML==='禁止查卷'){let t_bgc=document.getElementsByClassName('t-bgc fl')[7]let edit_history_url=t_bgc.getElementsByTagName('a')[0].hrefa_score.href=edit_history_url.replace('edit_history','detail')a_score.innerHTML='查看詳情'}}var autoPractice=(exam)=>{let search=exam.getElementsByClassName('board-bottom')[0]if(search){return}let examId=exam.getAttribute("data-exam-id")let sum=Number(/(.*)\u9898/.exec(exam.getElementsByClassName('board-det')[0].childNodes[1].getElementsByTagName('span')[0].innerText.trim())[1])let is_repeat=exam.getElementsByClassName('board-left')[0].childNodes[25].innerText.trim()==='允許'let template='<div class="fl board-bottom robot" style="width: 770px;"><div class="fl board-left" style=" height: 40px!important;line-height: 40px;font-size: 14px;padding: 0 10px;"><div class="progress-tar" style="width:70%;display: inline-block;"><span style="line-height: 20px;height: 20px;">刷題進度:</span><progress class="progress" value="30" max="100" style="width: 60%;border-radius: 2px;border-left: 1px #ccc solid;border-right: 1px #ccc solid;border-top: 1px #aaa solid;background-color: #eee;margin-bottom: 1px;">您的瀏覽器不支持progress元素</progress><span style="margin: 10px; line-height: 20px;"><span class="count-practice">0</span>/<span class="sum-practice"></span></span></div><div style="width: 30%;text-align: center;display: inline-block;"><span class="status-practice" style="margin: 10px;">正在xxxx</span></div></div><div class="fl board-right" style="height: 40px!important;line-height:40px;font-size:14px;background-color: #fe8333;cursor: pointer;color: white;"><div class="button-practice"></div></div></div>'//添加偽元素CSSdocument.styleSheets[0].addRule('progress::-webkit-progress-bar','background-color: #d7d7d7;'); // 支持IEdocument.styleSheets[0].addRule('progress::-webkit-progress-value','background-color: #aadd6a;'); // 支持IElet board_bottom=document.createElement('div')board_bottom.innerHTML=templateboard_bottom=board_bottom.childNodes[0]exam.appendChild(board_bottom)let button_practice=board_bottom.getElementsByClassName('button-practice')[0]let count_practice=board_bottom.getElementsByClassName('count-practice')[0]let sum_practice=board_bottom.getElementsByClassName('sum-practice')[0]let status_practice=board_bottom.getElementsByClassName('status-practice')[0]let progress=board_bottom.getElementsByClassName('progress')[0]sum_practice.innerHTML=sumprogress.value=0/sum*100count_practice.innerHTML=0let updateFlag=false;let now_sum=0;let updateStatus=(o)=>{now_sum=oif(updateFlag){return}else{let timer=setInterval(()=>{let now_num=Math.round(Number(count_practice.innerHTML))let cmp=now_sum-now_numif(cmp===0){updateFlag=false;clearInterval(timer);}else{if(now_num===0){now_num=1;}else{now_num=now_num+Math.round(cmp/Math.abs(cmp))}count_practice.innerHTML=now_numprogress.value=now_num/sum*100}},50)}}let refreshStatusSum=()=>{updateStatus(0)return $.ajax({url:'https://localost/MyZSTU/yooc/group/'+groupId+'/exam/'+examId+'/answer/total',type:'get',success:(res)=>{console.log(res)updateStatus(res.data)}})}if(is_repeat){button_practice.innerHTML="開始自動刷題"let autoPracticeStatus=falsebutton_practice.onclick=e=>{let exam_status=0let repeat=exam.getElementsByClassName('repeat')[0]if(repeat){if(autoPracticeStatus){autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL}else{autoPracticeStatus=truebutton_practice.innerHTML="關閉自動刷題"let repeat_url=repeat.getAttribute("repeat-url")let start_exam=exam.getElementsByClassName('start_exam')[0]if(start_exam){exam_status=0}else if(repeat){exam_status=4}let autoPracticeMain=()=>{if(!autoPracticeStatus){return}console.log("start")status_practice.innerHTML="刷題開始"console.log("apply-repeat")status_practice.innerHTML="申請重做"$.ajax({url: repeat_url,type : "POST",contentType: "application/x-www-form-urlencoded; charset=UTF-8",headers:{'X-CSRFToken':csrf},data: {'csrfmiddlewaresretoken': csrf},success: (res)=>{if(!autoPracticeStatus){return}status_practice.innerHTML="申請重做成功"let data=resif(data.result){console.log('申請重做成功')if(data.url){console.log("practice")if(!autoPracticeStatus){return}status_practice.innerHTML="申請考試頁面"$.ajax({url: data.url,type: 'GET',success: (res)=>{if(!autoPracticeStatus){return}status_practice.innerHTML="自動練習開始"let examuser=/var AnswerData = JSON.parse\(localStorage.getItem\("exam(.*)"\)\) \|\| {};/.exec(res)[1]console.log(examuser)repeat_url='https://www.yooc.me/group/'+groupId+'/exam/'+examId+'/examuser/'+examuser+'/repeat'let practice=document.createElement('html')practice.innerHTML=resconsole.log(practice)//獲取問題信息var question=Array.from(practice.getElementsByClassName('question-board'))let AnswerData={}question.forEach(q=>{console.log(q)let inputTag=q.getElementsByTagName('input')console.log(inputTag)if(inputTag.length>0){let Ele=inputTag[0]if(Ele.type==="radio"||Ele.type==="checkbox"){let arr=Ele.id.split('_')let questionId=arr[0]let name=arr[1]let qData=[arr[2]]AnswerData[questionId] = {};AnswerData[questionId][name] = qData;}else if(Ele.type==="text"){let Eles=Array.from(inputTag)Eles.forEach(e=>{e.value="test"let arr=e.id.split('_')let questionId=arr[0]let name=arr[1]AnswerData[questionId] = {};if (AnswerData[questionId][name]===undefined) {AnswerData[questionId][name] = [e.value.trim()];} else {AnswerData[questionId][name].push(e.value.trim());}})}}})status_practice.innerHTML="自動練習完成"console.log("save")localStorage.setItem("exam"+examuser,JSON.stringify(AnswerData));status_practice.innerHTML="提交答案"$.ajax({url: 'https://www.yooc.me/group/'+groupId+'/exam/'+examId+'/answer/save',type : "POST",contentType: "application/json; charset=UTF-8",headers:{'X-CSRFToken':csrf},data: JSON.stringify(AnswerData),success: (res)=>{ if(!autoPracticeStatus){return}status_practice.innerHTML="提交答案成功"console.log("submit")var submitUrl = 'https://www.yooc.me/group/'+groupId+'/exam/'+examId+'/answer/submit';var _AnswerData = [];for(let obj in AnswerData){var m = {};m[obj] = AnswerData[obj];_AnswerData.push(m);}var postData = {'csrfmiddlewaretoken': csrf,'answers': JSON.stringify(_AnswerData),'type': 0,'auto': 0,'completed':1};if(!autoPracticeStatus){return}status_practice.innerHTML="提交試卷"$.ajax({url: submitUrl,type : "POST",contentType: "application/x-www-form-urlencoded; charset=UTF-8",headers:{'X-CSRFToken':csrf},data: postData,success: (res)=>{if(!autoPracticeStatus){return}status_practice.innerHTML="提交試卷成功"console.log("upload")status_practice.innerHTML="申請答案頁面"getDetailPage(groupId,examId).then(detailPage=>{if(!autoPracticeStatus){return}status_practice.innerHTML="答案分析"let info=analysisDetailAnswerPage(detailPage)if(!autoPracticeStatus){return}status_practice.innerHTML="上傳答案"uploadAnswer(info.group,info.exam,info.questions).then(res=>{console.log(res)if(!autoPracticeStatus){return}status_practice.innerHTML="上傳成功"console.log("end")refreshStatusSum().then((res)=>{if(!autoPracticeStatus){return}console.log("update")status_practice.innerHTML="更新狀態"updateStatus(res.data)console.log("reboot")status_practice.innerHTML="正在重新開始"autoPracticeMain()},(e)=>{//頁面方法xAlert('失敗','網絡請求失敗')autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL})},(e)=>{//頁面方法xAlert('失敗','網絡請求失敗')autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL})},(e)=>{//頁面方法xAlert('失敗','網絡請求失敗')autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL})},error:(e)=>{//頁面方法xAlert('失敗','網絡請求失敗')autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL}});},error:(e)=>{//頁面方法xAlert('失敗','網絡請求失敗')autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL}})},error:(e)=>{//頁面方法xAlert('失敗','網絡請求失敗')autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL}})}}else{//頁面方法xAlert(data.message);autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL}},error:(e)=>{//頁面方法xAlert('失敗','網絡請求失敗')autoPracticeStatus=falsebutton_practice.innerHTML="開始自動刷題"window.location.href=document.URL}});}autoPracticeMain()}}else{//頁面方法xAlert('失敗','無法獲取重做按鈕,請測試允許反復練習并且確保有重做按鈕在頁面上')}}}else{button_practice.innerHTML="刷新刷題進度"button_practice.onclick=e=>{console.log("start")console.log("get")console.log("update")refreshStatusSum()console.log("end")}}//初始化狀態refreshStatusSum(res=>{},ajaxUsualErrorMessage)status_practice.innerHTML=""}let exams_board=document.getElementsByClassName('exams-board')[0]if(exams_board){let exams=Array.from( exams_board.getElementsByTagName('li'))if(exams||exams!==[]){exams.forEach(exam=>{autoPractice(exam)seeExam(exam)})}else{return}}}var detailPage=()=>{//獲取考試信息var group=document.getElementById('group-data')var groupId=group.getAttribute("data-group-id")var examId=group.getAttribute("data-exam-id")var examQuestionNum=Number(group.getAttribute("data-questions"))//獲取問題信息var questions=document.getElementsByClassName('question-board')var questionNum = questions.length//獲取答案信息var ansElements = document.getElementsByClassName('the-ans')var ansNum = ansElements.lengthvar addIdTag=()=>{//獲取問題信息var question=Array.from(document.getElementsByClassName('question-board'))question.forEach(q=>{let board_type=q.id.split('-')[0]let question_id=q.id.split('-')[1]let idTag=q.getElementsByClassName('question-id-tag')if(idTag.length===0){idTag=document.createElement('span')idTag.classList.add('question-id-tag')q.children[0].appendChild(idTag)}if(board_type==='question'){idTag.innerHTML=" 題目ID:"+question_id}else if(board_type==='answer'){idTag.innerHTML=" 答案ID:"+question_id}})}var nullSubmit=()=>{//獲取問題信息var question=Array.from(document.getElementsByClassName('question-board'))question.forEach(q=>{console.log(q)let inputTag=q.getElementsByTagName('input')console.log(inputTag)if(inputTag.length>0){let Ele=inputTag[0]if(Ele.type==="radio"||Ele.type==="checkbox"){if(Ele.type==="radio"){Ele.checked=true;}else if(Ele.type==="checkbox"){Ele.checked=true;}//頁面方法choiceAnswerData($(q))}else if(Ele.type==="text"){let Eles=Array.from(inputTag)Eles.forEach(e=>{e.value="test"})//頁面方法inputAnswerData($(q))}let ele_name=Ele.name.replace(/\_[0-9]+/, '')let questionTag=document.getElementById(ele_name)questionTag.classList.add('done')}})}var autoAnswer=()=>{var ansElements = Array.from(document.getElementsByClassName('the-ans'))let pattern=/\u6b63\u786e\u7b54\u6848\uff1a(.*)/ansElements.forEach(ansEle=>{let ans=ansEle.children[0].innerText.trim()if(pattern.test(ans)){var answers=pattern.exec(ans)[1]console.log(answers)let parentNode=ansEle.parentNodelet question_id=parentNode.id.split('-')[1]answers.split('、').forEach(answer=>{if(/[A-Z]/.test(answer)){let li_Eles=parentNode.getElementsByTagName('li')let li_Ele=li_Eles[answer.charCodeAt(0)-65]let input_id=li_Ele.dataset.questionName+"_"+li_Ele.dataset.questionValuelet Ele=document.getElementById(input_id)if(Ele.type==="radio"){Ele.checked=true;}else if(Ele.type==="checkbox"){Ele.checked=true;}//頁面方法choiceAnswerData($(document.getElementById('question-'+question_id)))}else{let input_id=question_id+"_" + (answers.indexOf(answer) + 1)let Ele=document.getElementById(input_id)Ele.value=answer//頁面方法inputAnswerData($(document.getElementById('question-'+question_id)))}})let questionTag=document.getElementById(question_id)questionTag.classList.add('done')}})}var appendsomething=()=>{var releaseButton=document.getElementsByClassName('release-board')[0]var ns=document.createElement('a')ns.id="null-submit"ns.href="javascript:;"ns.innerText="提交白卷"ns.style="margin-left: 0px;margin-top: 10px;"ns.title="隨機答案提交試卷"ns.onclick=()=>{nullSubmit()//頁面方法xAlert('提示','隨機答案選擇完畢,可以提交了')}releaseButton.appendChild(ns)var qa=document.createElement('a')qa.id="query-answer"qa.href="javascript:;"qa.innerText="查詢答案"qa.style="margin-left: 20px;margin-top: 10px;"qa.title="云端題庫查詢答案"qa.onclick=()=>{var ansElements = document.getElementsByClassName('the-ans')var ansNum = ansElements.lengthif(ansNum<0){answer()}else{//頁面方法xAlert('失敗','已經有答案了哦')}}releaseButton.appendChild(qa)var autoAnswerButton=document.createElement('a')autoAnswerButton.id="auto-answer-submit"autoAnswerButton.href="javascript:;"autoAnswerButton.innerText="自動答題"autoAnswerButton.style="margin-left: 0px;margin-top: 10px;"autoAnswerButton.title="答案自動選擇"autoAnswerButton.onclick=()=>{autoAnswer()//頁面方法xAlert('提示','答案自動選擇完畢,請自行檢查填空題部分')}releaseButton.appendChild(autoAnswerButton)}if(ansNum>0){if(questionNum===examQuestionNum){getDetailPage(groupId,examId).then(detailPage=>{let info=analysisDetailAnswerPage(detailPage)uploadAnswer(info.group,info.exam,info.questions).then(res=>{console.log(res)},ajaxUsualErrorMessage)},ajaxUsualErrorMessage)}else{console.log("現在是考試中,不能上傳答案哦。")}}else{//獲取問題信息questions=$('.question-board')var question_arr=[]questions.each((index,q)=>{question_arr.push(q.id.substr(9))})getAnswer(groupId,examId,question_arr).then(res=>{console.log(res)var questionContainer=document.getElementsByClassName('exam-detial-container')[0]res.forEach(q=>{var question=document.getElementById('question-'+q.id)var answer = document.createElement("div");answer.innerHTML = q.question;var child=answer.childNodes[0]child.id='answer-'+q.idquestionContainer.insertBefore(child,question)console.log(question)console.log(answer)})addIdTag()},ajaxUsualErrorMessage)appendsomething()unblock()}addIdTag() }var start=()=>{if(url!=location.pathname){url=location.pathnameconsole.log(url)if(url.match(/\/group\/[0-9]*\/exams.*/)){examsPage()}else if(url.match(/\/group\/[0-9]*\/exam\/[0-9]*\/detail/)){detailPage()}}}var int=self.setInterval(()=>{start()},1000); })();參考文章
https://blog.csdn.net/LPLIFE/article/details/80600123
https://www.cnblogs.com/lvdabao/p/jquery-deferred.html
https://www.w3school.com.cn/jquery/jquery_ref_selectors.asp
總結
以上是生活随笔為你收集整理的JavaScript——易班优课YOOC课群在线测试自动答题解决方案(十五)整合升级+引入jQuery的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL——统计某个表每天的总量和增量
- 下一篇: JavaScript——jQuery A