Я создал простой плагин jQuery для изменения элемента в синий цвет и может передать ему параметр, чтобы изменить элемент на заданный цвет.Расширение плагина jQuery для изменения конфигурации
Теперь я хочу создать новый плагин, который изменяет цвет на желтый, не передавая цвет в качестве параметра. Я прочитал https://stackoverflow.com/a/4414356/1032531, но, похоже, он описывает добавление метода к объекту.
Как это лучше всего выполнить?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Extend jQuery Plugin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
(function($){
var defaults = {
'color' : 'blue'
};
var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options);
return this.each(function() {
$(this).css('color',settings.color);
});
},
destroy : function() {
return this.each(function() {});
}
};
$.fn.changeColor = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.changeColor');
}
};
}(jQuery)
);
jQuery.fn.extend({
changeColorToYellow: function() {
//What do I do?
//$.changeColor({color:'yellow'})
}
});
$(function() {
$('#myElement1').changeColor();
$('#myElement2').changeColor({color:'red'});
$('#myElement3').changeColorToYellow();
});
</script>
</head>
<body>
<p id='myElement1'>myElement1</p>
<p id='myElement2'>myElement2</p>
<p id='myElement3'>myElement3</p>
</body>
</html>
Try: '$ (это) .changeColor ({цвет: 'желтый'});' – jcubic
@jcubic Спасибо. Кажется, работает. Это считается правильным подходом? Для моего реального приложения мне нужно передать несколько параметров, и я просто пытаюсь сделать мой скрипт более кратким. См. Http://jsbin.com/folutu/1/ – user1032531