gpt4 book ai didi

javascript - jQuery 脚本在 .load() 之后不起作用

转载 作者:行者123 更新时间:2023-11-28 20:05:53 25 4
gpt4 key购买 nike

我有 4 个页面通过加载“合并”为一个页面 (index.html):

<!-- !!!! Files includes !!!! -->
<script language="JavaScript" type="text/javascript">
$(function(){
$("#included1").load("aaa.html");
$("#included2").load("bbb.html");
$("#included3").load("ccc.html");
$("#included4").load("ddd.html");
});
</script>

并显示在此处:

<div id="content">
<section><br>
<div id="included1"></div>
</section>
<section><br>
<div id="included2"></div>
</section>
<section><br>
<div id="included3"></div>
</section>
<section><br>
<div id="included4"></div>
</section>
</div> <!-- end of content // text below menu-->

不幸的是,由于某些服务器限制以及这 4 个页面是由脚本在不同时间生成的事实,必须以这种方式完成。

每个页面的内部代码都有许多带有长文本的 block ,需要在某些操作中隐藏/显示。它看起来像这样:

<div class="error">
<div class="more">[... more]</div>
<div id="edetails" class="content small">
Error code///Error code///Error code///Error code///Error code///Error code///
Error code///Error code///Error code///Error code///Error code///Error code///
Error code///Error code///Error code///Error code///Error code///Error code///
</div>
</div><!-- end of error -->

为此,我使用这个:

<script type="text/javascript"> 
$(window).load(function(){
$('.more').click(function () {
if($(this).html()=="[... more]") {
$(this).html("[... less]");
$(this).next('#edetails').removeClass('small');
$(this).next('#edetails').addClass('normal');
} else {
$(this).html("[... more]");
$(this).next('#edetails').removeClass('normal');
$(this).next('#edetails').addClass('small');
};
});
});
</script>

如果我在每个页面上保留该代码,并打开该页面(例如 aaa.html,而不是 index.html) - 它就可以正常工作。

如果我打开index.html - 它根本不起作用。

所以...由于我将该代码 4 次标记到 index.html,我决定将其移动到索引并将其保留在 <head> 中。 - 实际上,当我在服务器上打开该页面时 - 显示/隐藏功能根本不起作用。

但是当我将 index.html 保存到硬盘并在浏览器中打开它时 - 它可以正常工作。

我不知道发生了什么......有什么想法吗?

最佳答案

这里棘手的部分是 jQuery.load() 是异步的。您需要同步调用以便能够在正确的时间运行脚本。我建议为此目的使用 jQuery.Deferred:

$(document).ready(function() {
function deferredLoad(target, url) {
return $.Deferred(function(deferred) {
$(target).load(url, function() {
deferred.resolve();
});
}).promise();
}

var loadPromises = [];

loadPromises.push(deferredLoad('#included1', 'aaa.html'));
loadPromises.push(deferredLoad('#included2', 'bbb.html'));
loadPromises.push(deferredLoad('#included3', 'ccc.html'));
loadPromises.push(deferredLoad('#included4', 'ddd.html'));

$.when.apply(null, loadPromises).done(function() {
$('.more').click(function () {
if($(this).html() == "[... more]") {
$(this).html("[... less]");
$(this).next('#edetails').removeClass('small');
$(this).next('#edetails').addClass('normal');
} else {
$(this).html("[... more]");
$(this).next('#edetails').removeClass('normal');
$(this).next('#edetails').addClass('small');
};
});
});
});

这样,当所有加载操作完成时,您的脚本就会运行。

关于javascript - jQuery 脚本在 .load() 之后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20841193/

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