[英]jQuery plugin functionality changing background color on click
我正在制作一个简单的插件函数,在单击时将元素的背景颜色变为红色。 我添加了如下所示的代码,但无法在点击时获得按钮的背景颜色。 有人可以更正代码吗?
<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>
你还没有定义 red
应该做什么。 你需要这样的东西:
$.fn.red = function(/*options object maybe?*/) {
return this.css( "background-color", "red" );
};
使用jQuery不需要像这样的内联事件:
$(function() {
$("button").on("click", function() {
$(this).red();
});
});
您应该先阅读本教程:
HTML :
<button id="red">Red</button>
CSS :
.red-cell {
background: #F00; /* Or some other color */
}
JS :
$( function() {
$('#red').click( function() {
$(this).toggleClass("red-cell");
});
});
你可以简单地重新编写你的javascript代码,如下所示,
$(document).ready(function(){
$(".button").click(function(){
$(this).css( "background-color", "red" );
});
})
要使其作为正确的插件工作,您必须将click
事件绑定到插件函数中的元素本身,如:
$.fn.red = function() {
$(this).each(function(){
var elem = $(this);
elem.bind('click',function(){
elem.css({backgroundColor:'red'})
});
});
};
现在您不必为每个元素一次又一次地调用click事件。 你可以为多个元素调用它,如下所示:
$('span,button').red();
你可以在这里看到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.