Jquery 的同步问题 - 没有警报就无法工作
我有几个按钮,当单击这些按钮时,我使用 Jquery 更改了它们的类。 我的问题是,只有当我先调用警报时它才有效。
我知道这一定是由于尚未加载的东西造成的, 但我不明白是谁以及为什么。
这是我的代码:
<input type="button" id="About" class="menu_button" value="About"/>
<input type="button" id="Contact" class="menu_button" value="Contact" />
<script>
$(".menu_button").click(function()
{
//alert("onMenuClick");
$(".menu_button").removeClass("menu_button_selected");
$(this).addClass("menu_button_selected");
});
</script>
谢谢!
I have a couple of buttons that when clicked, I changed their class using Jquery.
My problem is that its only works if I call an alert first.
I know this must be due to something that has not been loaded yet,
but I can't understand who and why.
This is my code:
<input type="button" id="About" class="menu_button" value="About"/>
<input type="button" id="Contact" class="menu_button" value="Contact" />
<script>
$(".menu_button").click(function()
{
//alert("onMenuClick");
$(".menu_button").removeClass("menu_button_selected");
$(this).addClass("menu_button_selected");
});
</script>
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这总是一件好事你应该总是将代码放在onload
事件中原因是,即使 DOM 树不存在,某些浏览器也会允许 JS 执行但已满载,并导致元素不存在或尚不可用。 jQuery 函数
$(function() { ... });
将确保仅当所有内容都已加载并准备就绪时才会运行其中的代码。** 更新 **
您的
script
标签应类似于此处< /a> 是对 jsfiddle 的测试,表明它适用于您给出的代码。如果它对你不起作用,那么你的问题就出在其他地方。我建议您使用 Google Chrome 及其开发者工具来调试 Javascript。
it is always a good thing toYou should always place your code inside anonload
eventThe reason being that, some browsers will allow JS to execute even if the DOM tree is not yet fully loaded, and leading to elements not present, or not yet available. The jQuery function
$(function() { ... });
will ensure that the code inside will be run only when everything is loaded and ready.** UPDATE **
Your
script
tags should look likeAnd here is a test on jsfiddle showing that it works for the code you gave. If it does not work for you, then your problem is somewhere else. I suggest you use Google Chrome and it's developper tool to debug your Javascript.
这个脚本在 Firefox 下对我来说工作得很好:
This script work fine for me under Firefox :
将您的代码包装在
$(function(){});
中,这意味着您的代码仅在 DOM 准备就绪时才会执行:Wrap your code in
$(function(){});
This means your code will only be executed when the DOM is ready for it: