您好,我尝试了多种解决方案,我可以找到论坛,但我认为我需要了解最基本的首先:)
我创建了一个我想要创建的插件的(非常)简化的例子,它在不同的DOM对象上使用鼠标事件,但现在单击所有div更改为'lime‘。我该如何解决这个问题呢?
<!doctype html>
<html>
<head>
</head>
<script src="jquery.js"></script>
<script>
(function ($, color, otherColor){
var otherColor= 'yellow';
$.fn.tester = function(color, otherColor){
otherColor= otherColor;
this.css('background-color', color);
this.on('click', changeColor);
}
function changeColor(e){
$(this).css('background-color', otherColor);
}
}(jQuery));
</script>
<script>
$(document).ready(function(){
$('#tester').tester('green', 'purple');
$('#tester2').tester('black', 'gray');
$('#tester3').tester('orange', 'lime');
});
</script>
<body>
<div id="tester" class="row tester" style="width:100%; height: 100px; background-color: #0ff;"></div>
<div id="tester2" class="row tester" style="width:100%; height: 100px; background-color: #0ff;"></div>
<div id="tester3" class="row tester" style="width:100%; height: 100px; background-color: #0ff;"></div>
</body>
</html>
发布于 2014-06-03 16:51:06
您需要将颜色保存在闭包中。如果使用全局变量,则它始终包含设置的最后一种颜色。
this.on("click", function() {
changeColor(this, otherColor);
});..。
function changeColor(element, color) {
element.css('background-color', color);
}https://stackoverflow.com/questions/24010735
复制相似问题