开发者

Synchronization problem with Jquery - not working without an alert

开发者 https://www.devze.com 2023-03-26 08:12 出处:网络
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 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_selec开发者_运维知识库ted");
            });


      </script>

Thanks!


it is always a good thing to You should always place your code inside an onload event

$(function() {
$(".menu_button").click(function()
            {
                //alert("onMenuClick");
                $(".menu_button").removeClass("menu_button_selected");
                $(this).addClass("menu_button_selected");
            });
});

The 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 like

<script type="text/javascript">
  // js here
</script>

And 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.


This script work fine for me under Firefox :

<script type="text/javascript">

$(document).ready(function() {


 $(".menu_button").bind('click',function()
       {
           //alert("onMenuClick");
           $(".menu_button").removeClass("menu_button_selected");
           $(this).addClass("menu_button_selected");
       });
}
</script>


Wrap your code in $(function(){}); This means your code will only be executed when the DOM is ready for it:

<script>    

    $(function(){

        $(".menu_button").click(function()
        {
            //alert("onMenuClick");
            $(".menu_button").removeClass("menu_button_selected");
            $(this).addClass("menu_button_selected");
        });

    });

</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消