简体   繁体   中英

jQuery plugin functionality changing background color on click

I am making a simple plugin function to turn the element's background color to red, on its click. I have added the code as shown below, but unable to get the background-color changed of the button on click. Can someone correct the code?

<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
       $.fn.red({
          red:function(){return this.each(function(){this.style.background=red;})}
       });
    </script>
  </head>
  <body>
    <button onclick="red()">Red</button>
  </body>
</html>

You have not defined what red should do. You'd need something like:

$.fn.red = function(/*options object maybe?*/) {
    return this.css( "background-color", "red" );
};

jsFiddle Example

And there is no need for an inline event like that, using jQuery:

$(function() {
    $("button").on("click", function() {
         $(this).red();
    });
});

You should have a read at this tutorial first:

https://learn.jquery.com/plugins/basic-plugin-creation/

HTML :

<button id="red">Red</button>

CSS :

.red-cell {
   background: #F00; /* Or some other color */
}

JS :

 $( function() {
  $('#red').click( function() {
    $(this).toggleClass("red-cell");
  });
 });

you can simply re write your javascript code as follows,

$(document).ready(function(){
    $(".button").click(function(){
        $(this).css( "background-color", "red" );
    });
})

fiddle : https://jsfiddle.net/nileshmahaja/v2cobdvv/

To make this work as a proper plugin, you have to bind the click event to the element itself in plugin function, like:

$.fn.red = function() {
    $(this).each(function(){
        var elem = $(this);
        elem.bind('click',function(){
            elem.css({backgroundColor:'red'})
        });
    });
};

now you don't have to call click event again and again for every element. you can call this for multiple elements, like this:

$('span,button').red();

you can see the jsfiddle here: http://jsfiddle.net/lokeshpahal/ghLssvos/3/

    function red() {    
        alert("fgdfg");    
        $("#btn").css("background-color", "red");
    }

    <input type="button" id="btn" onclick="red()" value="Red"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM