按钮大小和颜色变化

button size and color changing

我这里有 4 个按钮,但只有第一个按钮有效,我希望相同的 jquery 代码稍微改变一下,以便在所有这些按钮上工作... 我可以复制过去 jquery 4 次并更改它以工作,但我想要更简单和更少的代码,一个 jquery 怎么做?

CSS

.yellowBackground {    
    background-color: yellow;    
}

.redBackground {    
    background-color: red;
}

button.yellowBackground {    
    width:50px; 
    height:50px; 
}

HTML

<table>
    <tr>
      <td><button id="button"  class="yellowBackground">Pause</button></td>
      <td><button id="button"  class="yellowBackground">Pause</button></td>
      <td><button id="button"  class="yellowBackground">Pause</button></td>
      <td><button  id="button"  class="yellowBackground">Pause</button></td>
   </tr>
</table>

JS

$(function() {    
    $("#button").click(function() {    
        changeThumb();    
    });    
});

function changeThumb() {    
    $("#button").toggleClass("redBackground");    
}

ID 必须是唯一的您可以将处理程序添加到 class .yellowBackgroundbutton

$(function() {

    $(".yellowBackground").click(function() {

        $(this).toggleClass("redBackground");

    });

});

ID 必须是唯一的,您也可以使用 class 选择器 yellowBackground 来做到这一点,如下所示:

$(function() {
      $(".yellowBackground").click(function() {
      $(this).toggleClass("redBackground");
    });
 });

FIDDLE DEMO

您还错过了在 <table> 中打开 <tr> 标签 html.Please 更正

在选择 class 或 JQuery 选择中的 id 之前指定元素:

$(function() {

$('button#button').click(function() {

        $(this).toggleClass("redBackground");

    });

});