gpt4 book ai didi

Javascript Jquery 在外部样式表更改/重新加载 promise 方式后执行代码

转载 作者:行者123 更新时间:2023-11-28 06:24:44 25 4
gpt4 key购买 nike

我有一个包含几个主题的页面,并允许用户通过组合框进行更改。在组合框的 change 事件中,我使用 jquery 删除当前样式表并附加新样式表。现在我想在新样式表完成加载后运行一些代码(重新计算元素的大小,...)。

我想知道我能否以 promise 的方式做到这一点?目前我正在使用 setTimeout 但我认为时机不够好。我在想类似的事情:

var oldStylesheet = ...;
var newStylesheet = ...;

$.when(function() {
var d = $.Deferred;

oldStylesheet.remove();
newStylesheet.append();

// when new stylesheet completed loading: d.resolve();

return d.promise;
}).done(function() {
// code to run after new stylesheet has completed loading
});

最佳答案

您可以在 jQuery 中为您的用例使用 $.get() AJAX 函数,假设您在组合框中的选项值是样式表的 url:

var oldStylesheet = ...;
$('.theme-select').on('change', function(){
var stylesheet = $(this).val();
$.get(stylesheet , function(response){
oldStylesheet.remove();
// Check if the style tag in which the file will be appended is in place
// if not create one
if (!$('.custom-theme').length){
$('head').append('<style class="custom-theme"></style>');
}
// Add/Replace the new style with the old one.
$('.custom-theme').text(response);
});
});

虽然我还没有测试过,所以我不知道是否有错误。

关于Javascript Jquery 在外部样式表更改/重新加载 promise 方式后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35355724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com