我正在学习将函数转换为插件。并将函数转换为插件似乎很简单。但是如果我有两个函数相互对应怎么办 - 那我怎么能将这两个函数转换成一个插件呢?
比如我有这些函数用于制作jquery幻灯片,
function run_slide(target_slide) {
//add a class the the first element
$('li:first-child',target_slide).addClass('active');
//Set the opacity of all images to 0
$('.slide li').css({opacity: 0.0});
//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
setInterval('loop_slide("'+target_slide+'")',5000);
}
function loop_slide(target_slide) {
//Get next image, if it reached the end of the slideshow, rotate it back to the first image
var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('.slide li:first-child') :current.next()) : $('.slide li:first-child'));
//Set the fade in effect for the next image, show class has higher z-index
current.addClass('last-active');
next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function(){
current.animate({opacity: 0.0}, 1000).removeClass('active last-active');
$('.caption p',target_slide).html(caption_description);
});
}
这就是我调用这些函数的方式,
run_slide('#slide');
理想情况下,我想从插件方法中调用这些函数,
$('#slide').run_slide();
但是如何将这两个函数包装到下面的插件制作方法中,如jquery's documenation,
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
感谢。
答案 0 :(得分:5)
根据jquery的文档/样式指南,单个插件不应该使用多个条目混淆$ .fn命名空间。但是你的单个插件需要多个功能,因为你已经绘制了它。答案是像这样的单例:http://docs.jquery.com/Plugins/Authoring#Namespacing第一个代码块是你不应该做的。第二个是你应该做的。您可以创建一个包含所有方法的单例。通过范围关闭,单例可用于您的插件$ .fn ...调用。通过这种方式,您的插件可以同时处理多个DOM对象,同时不会混乱jquery命名空间,或者运行多个函数实例的内存空间。所有的胜利:))
答案 1 :(得分:1)
答案 2 :(得分:1)
这样的事情:
$(function() {
$.fn.run_slide = function {
var target_slide = $(this);
//add a class the the first element
$('li:first-child', target_slide).addClass('active');
//Set the opacity of all images to 0
$('.slide li').css({
opacity: 0.0
});
//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
setInterval(function() {
target_slide.loop_slide();
}, 5000);
}
$.fn.loop_slide = function() {
var target_slide = $(this);
//Get next image, if it reached the end of the slideshow, rotate it back to the first image
var next = ((current.next().length) ? ((current.next().hasClass('caption')) ? $('.slide li:first-child') : current.next()) : $('.slide li:first-child'));
//Set the fade in effect for the next image, show class has higher z-index
current.addClass('last-active');
next.css({
opacity: 0.0
}).addClass('active').animate({
opacity: 1.0
}, 1000, function() {
current.animate({
opacity: 0.0
}, 1000).removeClass('active last-active');
$('.caption p', target_slide).html(caption_description);
});
}
});
或者您也可以在插件中定义另一个函数,如下所示:
$.fn.run_slide = function(){
function loop_slide(){
//...
}
loop_slide.call(this);
}