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="#"></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="#"></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 badges4 Answers
Reset to default 6Try 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
版权声明:本文标题:javascript - Button element click event to toggleClass doesn't work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742011265a2412926.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论