点击时切换按钮背景颜色

时间:2022-01-26 20:31:28

can some one help me with this please http://jsfiddle.net/ukkj7dth/5/

有人可以帮我这个请http://jsfiddle.net/ukkj7dth/5/

it works perfectly on toggling buttons but i don't why it's working on jsfiddle and not working in my page. do i need some js file?

它完美地适用于切换按钮,但我不知道为什么它在jsfiddle工作而不在我的页面中工作。我需要一些js文件吗?

<div class="button">button 1</div>
<div class="button">button 2</div>
<div class="button">button 3</div>
<div class="button">button 4</div>
<div class="button">button 5</div>
<div class="button">button 6</div>

1 个解决方案

#1


0  

You want to fire the code on DOM ready like so:

您想要在DOM上准备好代码,如下所示:

$(function() { //<<<<----
    $('.button').on('click', function() {
        $(this).toggleClass('myClass').siblings().removeClass('myClass');
    });
}); //<<<<----

It works in jsfiddle because you're firing the code on window load ... see onLoad in dropdown. If you set jsfiddle to no wrap in <head> it'll stop working -- which would be close to what you might have in your application.

它在jsfiddle中工作,因为你在窗口加载时触发代码...在下拉列表中查看onLoad。如果你将jsfiddle设置为中没有换行,那么它将停止工作 - 这将与您在应用程序中的内容相近。

Does Not Work

不起作用

Works

作品

#1


0  

You want to fire the code on DOM ready like so:

您想要在DOM上准备好代码,如下所示:

$(function() { //<<<<----
    $('.button').on('click', function() {
        $(this).toggleClass('myClass').siblings().removeClass('myClass');
    });
}); //<<<<----

It works in jsfiddle because you're firing the code on window load ... see onLoad in dropdown. If you set jsfiddle to no wrap in <head> it'll stop working -- which would be close to what you might have in your application.

它在jsfiddle中工作,因为你在窗口加载时触发代码...在下拉列表中查看onLoad。如果你将jsfiddle设置为中没有换行,那么它将停止工作 - 这将与您在应用程序中的内容相近。

Does Not Work

不起作用

Works

作品