admin管理员组

文章数量:1321259

I have a on/off button that is featured here

I have all the elements in place and im expecting the button class .on to initiate when pressed.

Only it wont work no matter what i try.

i added the exact code in jsFiddle, it works there, but not on my page.

  • jsFiddle
  • My page

I'm adding the HTML inside jquery:

'<section>'+
        '<button id="button" href="#">&#xF011;</button>'+
    '<span>'+
    '</span>'+
'</section>'+

I'm guessing its a conflict between CSS elements but i cant pinpoint the problem.

Any thoughts?

I have a on/off button that is featured here

I have all the elements in place and im expecting the button class .on to initiate when pressed.

Only it wont work no matter what i try.

i added the exact code in jsFiddle, it works there, but not on my page.

  • jsFiddle
  • My page

I'm adding the HTML inside jquery:

'<section>'+
        '<button id="button" href="#">&#xF011;</button>'+
    '<span>'+
    '</span>'+
'</section>'+

I'm guessing its a conflict between CSS elements but i cant pinpoint the problem.

Any thoughts?

Share Improve this question edited Jan 27, 2013 at 21:07 Boaz 20.2k9 gold badges66 silver badges72 bronze badges asked Jan 27, 2013 at 20:48 TonalDevTonalDev 5831 gold badge8 silver badges22 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Try this

<script type="text/javascript">
    $(document).ready(function(){
        $('#button').on('click', function(){
            $(this).toggleClass('on');
        });
    })
</script>

In jsFiddle you are correctly binding the event within $(document).ready(), while in your own page you are not. So in jsFiddle, the event is correctly bound to the button element only after the DOM is ready, while in your own page the event fails to bind since the element does not exist yet at that stage.

I can see this in your page's HTML:

<script>
   $(function(){
      $('#player').metroPlayer();
   });
</script>
<script type="text/javascript">
   $('#button').on('click', function(){
      $(this).toggleClass('on');
   });
</script>

You need to place your on() function inside the $(function() { ... });

Try this

 $(document).ready(function(){
      $('#button').click(function(){
         $(this).toggleClass('on');
      });
    });

本文标签: javascriptButton element click event to toggleClass doesn39t workStack Overflow