jQuery 就绪功能在 WordPress 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1327085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery ready function doesn't work in WordPress
提问by squarecandy
I'm using jQuery at WordPress (@the HOME page) and the ready function doesn't work for me. I have a index.php which is including (php) a header, footer and a sidebar. I tested this code:
我在 WordPress(@the HOME 页面)上使用 jQuery,而 ready 函数对我不起作用。我有一个 index.php,其中包括 (php) 页眉、页脚和侧边栏。我测试了这段代码:
<script type="text/javascript" src="path_to_jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert ("test text");
});
</script>
The alert (with the text "test text"
) is just not popping up immediately! It's only popping up after my sidebar has been loaded. This means while I'm seeing the index page (sidebar is not loaded yet) I have to wait a few seconds until the sidebar has finished loading, and only then the jQuery code is executed: the alert is popping up. So the ready function just wont work.
Can anybody tell me why and how I can solve this problem? Thanks.
警报(带有文本"test text"
)只是没有立即弹出!它只会在我的侧边栏加载后弹出。这意味着当我看到索引页面(侧边栏尚未加载)时,我必须等待几秒钟,直到侧边栏完成加载,然后才执行 jQuery 代码:弹出警报。所以 ready 函数就行不通了。谁能告诉我为什么以及如何解决这个问题?谢谢。
回答by squarecandy
within the WordPress environment, use this:
在 WordPress 环境中,使用这个:
jQuery(function($){
// now you can use jQuery code here with $ shortcut formatting
// this executes immediately - before the page is finished loading
});
jQuery(document).ready(function($){
// now you can use jQuery code here with $ shortcut formatting
// this will execute after the document is fully loaded
// anything that interacts with your html should go here
});
回答by Vidal Quevedo
The alert is popping up after the sidebar is loaded because ready() is supposed to be executed AFTER the whole page is done loading.
加载侧边栏后会弹出警报,因为 ready() 应该在整个页面加载完成后执行。
回答by Arjan
The alert (with the text "test text") is just not popping up immediately! It's only popping up after my sitebar has been loaded.
警报(带有文本“测试文本”)并没有立即弹出!它仅在我的站点栏加载后弹出。
That's exactly the advantageof using ready
. When you want it to popup right away, simply do
这正是优势利用ready
。当您希望它立即弹出时,只需执行
<script type="text/javascript">
alert ("test text");
</script>