Javascript jQuery插件功能在单击时更改背景颜色
我正在制作一个简单的插件函数,在点击时将元素的背景颜色变成红色。我已经添加了如下所示的代码,但无法在单击时更改按钮的背景色。有人能纠正代码吗Javascript jQuery插件功能在单击时更改背景颜色,javascript,jquery,function,plugins,Javascript,Jquery,Function,Plugins,我正在制作一个简单的插件函数,在点击时将元素的背景颜色变成红色。我已经添加了如下所示的代码,但无法在单击时更改按钮的背景色。有人能纠正代码吗 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $.fn.red({
<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>
$.fn.red({
红色:函数(){返回this.each(函数(){this.style.background=red;})}
});
红色
HTML:
<button id="red">Red</button>
.red-cell {
background: #F00; /* Or some other color */
}
$( function() {
$('#red').click( function() {
$(this).toggleClass("red-cell");
});
});
JS:
<button id="red">Red</button>
.red-cell {
background: #F00; /* Or some other color */
}
$( function() {
$('#red').click( function() {
$(this).toggleClass("red-cell");
});
});
您尚未定义红色<代码>应该执行的操作。你需要一些类似的东西:
$.fn.red = function(/*options object maybe?*/) {
return this.css( "background-color", "red" );
};
使用jQuery,不需要这样的内联事件:
$(function() {
$("button").on("click", function() {
$(this).red();
});
});
您应该首先阅读本教程:
您只需重新编写javascript代码,如下所示:
$(document).ready(function(){
$(".button").click(function(){
$(this).css( "background-color", "red" );
});
})
fiddle:要使此插件作为正确的插件工作,必须将
单击事件绑定到插件函数中的元素本身,如:
$.fn.red = function() {
$(this).each(function(){
var elem = $(this);
elem.bind('click',function(){
elem.css({backgroundColor:'red'})
});
});
};
现在,您不必为每个元素反复调用click事件。可以对多个元素调用此函数,如下所示:
$('span,button').red();
您可以在这里看到jsfiddle
:函数red(){
警报(“fgdfg”);
$(“#btn”).css(“背景色”、“红色”);
}
虽然这个答案似乎有效,但为什么不使用问题中的函数呢?亲爱的,我需要它!我知道通过jQuery的简单方法。亲爱的,我需要使用插件。我知道简单的方法!是的,它做到了!我需要插件的方式,它的工作!几句话的解释会使这个例子更好。