[英]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. 你还没有定义
red
应该做什么。 You'd need something like: 你需要这样的东西:
$.fn.red = function(/*options object maybe?*/) {
return this.css( "background-color", "red" );
};
And there is no need for an inline event like that, using jQuery: 使用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/ https://learn.jquery.com/plugins/basic-plugin-creation/
HTML : HTML :
<button id="red">Red</button>
CSS : CSS :
.red-cell {
background: #F00; /* Or some other color */
}
JS : JS :
$( function() {
$('#red').click( function() {
$(this).toggleClass("red-cell");
});
});
you can simply re write your javascript code as follows, 你可以简单地重新编写你的javascript代码,如下所示,
$(document).ready(function(){
$(".button").click(function(){
$(this).css( "background-color", "red" );
});
})
fiddle : https://jsfiddle.net/nileshmahaja/v2cobdvv/ 小提琴: 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: 要使其作为正确的插件工作,您必须将
click
事件绑定到插件函数中的元素本身,如:
$.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. 现在您不必为每个元素一次又一次地调用click事件。 you can call this for multiple elements, like this:
你可以为多个元素调用它,如下所示:
$('span,button').red();
you can see the jsfiddle
here: http://jsfiddle.net/lokeshpahal/ghLssvos/3/ 你可以在这里看到
jsfiddle
: http : //jsfiddle.net/lokeshpahal/ghLssvos/3/
function red() {
alert("fgdfg");
$("#btn").css("background-color", "red");
}
<input type="button" id="btn" onclick="red()" value="Red"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.