gpt4 book ai didi

javascript - 尝试隐藏文档,直到它被 JavaScript 更新

转载 作者:行者123 更新时间:2023-11-28 04:37:10 25 4
gpt4 key购买 nike

这是我的就绪处理:

$(document).ready(function() {
$(document).hide();

$('.foo').each(function(elem, i) {
$(elem).text('So long and thanks for all the fish');
});

$(document).show();
}};

我想做的是完全隐藏文档,直到一切都按照我的意愿准备就绪,但似乎 show() 函数不会等待元素迭代。

顺便说一句,我尝试将 show()hide() 更改为 css('display', 'hide')css('display', 'block') 但是,您仍然可以看到文字在您眼中发生变化。

如何确保所有代码在调用 show() 之前运行?

最佳答案

假设您通过隐藏正文或容器元素来解决此问题。这行不通,原因如下:

在(大部分)加载文档之后但隐藏文档之前发生了什么?

没错,尽管您尽了最大努力,文档仍可能会在那段时间内显示。

所以你可以做的是使用隐藏的 CSS 类,比方说,body无需任何 JavaScript 干预。例如:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
body.hide { display: none; }
</style>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready( function() {
$('.foo').each(function( i, elem ) {
$(elem).text( 'So long and thanks for all the fish' );
});
$('body').removeClass( 'hide' );
});
</script>
</head>
<body class="hide">
<div class="foo"></div>
</body>
</html>

当然,这确实意味着如果 JavaScript 被禁用,您的文档将完全不可见。如果你想要一个非 JavaScript 的回退怎么办?在那种情况下,你可以这样做。我们将隐藏 html元素而不是 body因为这样我们就知道代码可以在 head 中工作(body 元素此时可能还不存在),并且仅在启用 JavaScript 时隐藏它:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
html.hide { display: none; }
</style>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('html').addClass( 'hide' );
$(document).ready( function() {
$('.foo').each(function( i, elem ) {
$(elem).text( 'So long and thanks for all the fish' );
});
$('html').removeClass( 'hide' );
});
</script>
</head>
<body>
<div class="foo">
This content is displayed if JavaScript is disabled.
</div>
</body>
</html>

现在你有一个非 JavaScript 的回退,但是当启用 JavaScript 时文档仍然会立即隐藏,因为添加了 hide 的代码。类。

另请注意,您在 $().each() 中颠倒了参数打回来。 (有趣的是,您使用的顺序更有意义,并且确实是较新的 native .forEach() 函数使用的顺序。$().each() 中的顺序确实是倒退的 - 其中一个在当时看来是个好主意但真的只是一个错误。)

关于javascript - 尝试隐藏文档,直到它被 JavaScript 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16631522/

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