2016-04-28 13 views
2

ボタンの数があります。クリックイベントのボタンのスタイルを変更したいのですが、別のボタンをクリックした後デフォルトに変更... 私は私のスクリプトがあるクリック時のボタンのスタイルを変更して別のボタンをクリックする方法デフォルトに変更する必要があります

<table class="table"> 
    <thead> 
    <tr> 
     <th style="text-align: center;">Tables</th> 
    </tr> 
    </thead> 
    <tbody> 
    @foreach($tables as $table) 
    <tr id="table"> 
     <td style="text-align: center;"> 
     <button class="btn" >{{$table->table_no}} </button> 
     </td> 
    </tr> 
    @endforeach 
    </tbody> 
</table> 

のようにDBからボタンを取得しています:

$('#table button').click(function(){ 
    $(this).css('background-color','green'); 
    }); 

問題は、私はそのボタンの異なるボタンの背景色をクリックすると、デフォルトに変更する必要がありますですどのように私はこれを得ることができますか? PLZヘルプ、あなたより。

答えて

4

IDはので、私は行からIDを削除ユニークである必要があります。

また、インラインCSSをスタイルシートに移動しました。

あなたのループコンテンツは

$(function() { 
 
    $('#table button').on("click",function(e){ 
 
    e.preventDefault(); 
 
    $('#table button').removeClass("selected"); 
 
    $(this).addClass("selected"); 
 
    }); 
 
});
#table th,td { text-align: center; } 
 
.selected { background-color:green }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table id="table" class="table"> 
 
    <thead> 
 
    <tr> 
 
     <th>Tables</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td> 
 
     <button class="btn" >{{$table->table_no}} </button> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <button class="btn" >{{$table->table_no}} </button> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <button class="btn" >{{$table->table_no}} </button> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <button class="btn" >{{$table->table_no}} </button> 
 
     </td> 
 
    </tr> 
 

 
    </tbody> 
 
</table>

+0

ありがとうございます、しかし、私はテーブルの番号を知らない、データベースからテーブルを取得しています – JohnB

+0

私のコードはテーブルの数を気にしません。 – mplungjan

+0

ありがとう、それは間違いなく私を助けるでしょう。 – JohnB

0

あなたはあなたのスタイルに以下を追加、だけCSSによってこれを行うことができます。

button { 
    background: grey; 
} 
button:active { 
    background: green; 
} 
+0

これはボタンが押されている間だけ緑色になります – mplungjan

関連する問題