【问题标题】:jQuery plugin functionality changing background color on clickjQuery插件功能在点击时改变背景颜色
【发布时间】:2015-06-27 02:28:24
【问题描述】:

我正在制作一个简单的插件功能,在点击时将元素的背景颜色变为红色。我添加了如下所示的代码,但无法在单击时更改按钮的背景颜色。有人可以更正代码吗?

<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>

【问题讨论】:

    标签: javascript jquery function plugins


    【解决方案1】:

    你还没有定义red 应该做什么。你需要类似的东西:

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

    jsFiddle Example

    并且不需要像这样的内联事件,使用 jQuery:

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

    您应该先阅读本教程:

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

    【讨论】:

    • 是的,它做到了!我需要插件方式,它的工作原理......!谢谢。
    【解决方案2】:

    HTML

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

    CSS

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

    JS

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

    【讨论】:

    • 虽然这个答案似乎有效,但你为什么不使用问题中的函数?
    • 亲爱的插件我需要它!我知道通过 jQuery 的简单方法。
    【解决方案3】:

    你可以简单地重写你的javascript代码,如下所示,

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

    小提琴:https://jsfiddle.net/nileshmahaja/v2cobdvv/

    【讨论】:

    • 亲爱的插件我需要做。我知道简单的方法!
    【解决方案4】:

    要使它作为一个合适的插件工作,您必须在插件函数中将click 事件绑定到元素本身,例如:

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

    现在您不必为每个元素一次又一次地调用 click 事件。您可以为多个元素调用它,如下所示:

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

    你可以在这里看到jsfiddlehttp://jsfiddle.net/lokeshpahal/ghLssvos/3/

    【讨论】:

      【解决方案5】:
          function red() {    
              alert("fgdfg");    
              $("#btn").css("background-color", "red");
          }
      
          <input type="button" id="btn" onclick="red()" value="Red"/>
      

      【讨论】:

      • 几句话的解释会使这个例子更好。
      猜你喜欢
      • 1970-01-01
      • 2020-11-28
      • 2015-02-10
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多