最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Button element click event to toggleClass doesn't work - Stack Overflow

programmeradmin0浏览0评论

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');
      });
    });
发布评论

评论列表(0)

  1. 暂无评论