需要能够使用适用于所有按钮的代码来定位单个按钮

时间:2015-04-25 21:20:58

标签: html css

单击其中一个按钮时,我需要按钮更改为带有白色文本的红色背景。这需要适用于稍后添加的任何新按钮。如果不单独调整每个按钮,我怎么能这样做?

这是我的代码:

<!DOCTYPE html>

<html> 

  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
    <title>Page 2</title>

    <style type="text/css">
    /* Your styles go here */
    img {
        width:200px; 
        height:100px; 
        animation: widthChange 3s 2s;
        -webkit-animation: widthChange 3s 2s;
        -moz-animation: widthChange 3s 2s;
        -0-animation: widthChange 3s 2s;


    }

    p {text-align:center}
    button {margin:20px}
    .stylized {
        font-style: italic;
        border-width: 5px;
        border-color: yellow;
        border-style: outset;
    }

    @-webkit-keyframes widthChange {
        0%, 100% {width: 200px;}
        50% {width: 400px;}
    }
    @-o-keyframes widthChange {
        0%, 100% {width: 200px;}
        50% {width: 400px;}        }
    @-moz-keyframes widthChange {
        0%, 100% {width: 200px;}
        50% {width: 400px;}
    }
    @keyframes widthChange {
        0%, 100% {width: 200px;}
        50% {width: 400px;}

    }

    </style>

    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
       // jQuery methods go here...
       $(document).ready(function() {
        $('img').addClass("loaded");
        $('img').addClass("loaded2");
        $("#button1").click(function() {
            $("button").addClass("stylized");
            $("#button1").html("Fancy Button 1");
            $("#button2").html("Fancy Button 2");
            $("#button3").html("Fancy Button 3");
        });
       });

    });
    /* Your additional JavaScript goes here */
    </script>
  </head>

  <body>
    <img class = "image" src="elephant.jpg" alt="elephant"/>
    <p><button id="button1">Button 1</button><button id="button2">Button 2</button><button id="button3">Button 3</button></p>

  </body>
</html>

1 个答案:

答案 0 :(得分:1)

使用带有.on函数的jquery选择器。 然后参考函数内部的$(this)来更改特定按钮的属性。

编辑:您必须将其绑定到文档,因此如果添加新按钮,则可以在.on()函数选择器参数中选择它们。像这样:

$(document).ready(function() {

  $(document).on('click', "input[type='button']", function(e) {

    // Only for sample
    if ($(this).prop('id') == "addb") {
      $("#buttons").append("<input type='button' value='another button'><br>");
      return;
    }
    // end sample code


    $(this).css({
      backgroundColor: "red",
      color: "#fff"
    });

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" value="add more buttons" id="addb">
<br>
<br>

<div id="buttons">
  <input type="button" value="hello">
  <br>
</div>