使用下面的代码,我可以使用ajax成功地将一个CSS文件加载到我的head部分。
当我试图通过以下两种代码加载两个或多个css文件时,问题就开始了。
$("#getCustomCSS a").click(function() {
$.get('https://website.com/post-2709.css ,
https://website.com/post-1506.css', function(data) {
var style = document.createElement('style'),
head = document.getElementsByTagName('head')[0] || document.documentElement;
style.type = "text/css";
style.textContent = style.text = data;
head.appendChild(style, head.firstChild);
console.log( "Click GET CSS 2709 & 1506 Successful!" );
});
$("#pageMenuHome").removeClass("On");
$(".hamburger").removeClass("is-active");
console.log( "Click GET CSS Successful!" );
$('html, body').animate({scrollTop : 0},1500);
});
或变2
$("#getCustomCSS a").click(function() {
$.get('https://website.com/post-2709.css', function(data) {
var style = document.createElement('style'),
head = document.getElementsByTagName('head')[0] || document.documentElement;
style.type = "text/css";
style.textContent = style.text = data;
head.appendChild(style, head.firstChild);
console.log( "Click GET CSS 2709 Successful!" );
});
$.get('https://website.com/post-1506.css', function(data) {
var style = document.createElement('style'),
head = document.getElementsByTagName('head')[0] || document.documentElement;
style.type = "text/css";
style.textContent = style.text = data;
head.appendChild(style, head.firstChild);
console.log( "Click GET CSS 1506 Successful!" );
});
$("#pageMenuHome").removeClass("On");
$(".hamburger").removeClass("is-active");
console.log( "Click GET CSS Successful!" );
$('html, body').animate({scrollTop : 0},1500);
});
当前在点击,控制台显示“点击获得CSS成功!”但没有显示“点击获得CSS 2709成功!”然而,jquery工作,样式表被添加到头部。
我想要的:
发布于 2019-09-28 17:11:41
我可以在元素单击上下载多个CSS或JS文件:
(有一个与AJAX有关的警告。如果您正在使用ajax调用,则此代码只会在ajax调用之前检索和下载文件。调用之后-代码不执行。对于如何克服这一问题,我们将不胜感激。)
$('.getCSS a').one('click', function(e) {
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("/post-1841.css", "css")
loadjscssfile("/post-1886.css", "css")
loadjscssfile("/customcode.js", "js")
loadjscssfile("/post-2299.css", "css")
loadjscssfile("/post-2296.css", "css")
loadjscssfile("/post-1680.css", "css")
loadjscssfile("/post-1598.css", "css")
console.log( "ALL CSS & JS Downloaded" );
});
https://stackoverflow.com/questions/57547572
复制相似问题