javascript - 如果脚本已经存在,则从 head 标记中删除脚本
问题描述
所以我在另一个文件夹中调用一个函数,该函数继续下载一个库(jsPDF),然后运行生成的代码。但是,每次我单击触发函数调用的按钮时,脚本都会添加到头部,最终导致程序停止工作。我试图只添加一次脚本,如果添加了它们,请不要添加它们,而是继续使用其余代码。
调用运行函数
var myBtn = document.getElementById('submit1');
//add event listener
myBtn.addEventListener('click', function(event) {
fetch()
});
async function fetch(){
const itemToStore = document.getElementsByClassName("itemName");
const itemQty = document.getElementsByClassName("quoteQty");
const itemPrices = document.getElementsByClassName("quotePrice");
const itemTotal = document.getElementsByClassName("quoteTotal");
const totalCost = "Total Cost" + ":" + document.getElementById("quoteTotalCost").innerText;
fn(itemToStore, itemQty, itemPrices, itemTotal, totalCost)
// getFile()
}
js代码
async function functionCall(){
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++){
if(scripts[i].getAttribute('src') == 'https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.28/jspdf.plugin.autotable.js'){
console.log('found once')
break;
}
else{
console.log('not found')
var jQueryScript = document.createElement('script');
var pdfScript = document.createElement('script');
var tableScript = document.createElement('script');
var actualTable = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
pdfScript.setAttribute('src','https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js');
tableScript.setAttribute('src','https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js');
actualTable.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.28/jspdf.plugin.autotable.js');
document.head.appendChild(jQueryScript);
document.head.appendChild(pdfScript);
document.head.appendChild(tableScript);
document.head.appendChild(actualTable);
break;
}
}
return true;
}
function fn(a,b,c,e,f) {
functionCall().then(() => {
//rest of the code
错误信息
("jQuery.Deferred exception: doc.autoTable is not a function TypeError: doc.autoTable is not a function")
以及一条错误消息说 .then 未定义。
解决方案
推荐阅读
- python - Keras 进度条显示什么?
- javascript - 邮递员:TypeError:User.findOne 不是函数
- vba - 如果另一个单元格具有特定值,则想要禁用单元格编辑
- solidity - 在构造函数中设置默认值
- javascript - 使用分页时如何在 Webix 数据表中重新加载当前页面?
- java - 给定服务器端可用的字节数组和内容类型,如何使休息服务顺利下载?
- c# - 在 Visual Studio 中添加类时将默认类类型设置为 C# 类
- delphi - 错误消息 = 找不到 -lbz2 的库
- javascript - 使用jquery根据日期选择选项
- jquery - jquery 查询字符串为空