jquery插件:将函数转换为插件? [英] jquery plugin: converting functions into a plugin?

查看:101
本文介绍了jquery插件:将函数转换为插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习编写jquery插件,因此我认为通过将我的函数转换为插件来学习它会更容易,例如:



这些是我的正常功能,

  this.delete_uploaded = function(){

$ (.delete-uploaded)。click(function(){

//删除弹出。
$('#popup_result')。remove();

//同:var target_delete = $(this).parent()。parent()。parent();
var target_delete = $(this).parents('。item-uploaded'); //删除项目,例如li
var parent_delete = $(this).parents('。items-uploaded'); //保存删除项目的父项目,例如ul> li
var wrapper_parent = $(this).parents('。upload'); //包含父级的包装器,例如div> ul> li
var target_loadin = $(this)。 parent();
var target_html = $(this).parent()。html();
var path_load = $(this).attr('href');

//制作一个gif加载器。
target_loadin.html('< img src ='+ http_root + rp_image_global + img_loader +'style =float:none;/> loading');

//载入删除表单。
target_loadin.load(path_load,function(){

//当yes按钮被触发时。
$(input [type = submit] [name = yes] ).click(function(){

//从表单中的action的属性获取路径
var path_post = $(this).parent('form')。attr( 'action');
// alert(path_post);

//创建一个gif加载器
target_loadin.html('< div class =ajaxloader> < img src ='+ http_root + rp_image_global + img_loader +'style =float:none;/>正在载入< / div>');

//发布表单。
$ .post(path_post,$(this).serialize(),function(xml){

//处理表单输出
process_delete_uploaded(xml);
});

//向上滑动已删除的目标
target_delete.slideUp('fast',funct ion(){

//完全移除它的div
target_delete.remove();
//alert($('li',parent_delete).length);

//计算有多少物品落后
if($('li',parent_delete).length == 0)
{
$('。 ({
borderBottom:'0px solid#999',
padding:'0px 0px 0px 0px'
});
}

});

返回false;
});

//当触发no / cancel按钮时。
$(input [type = button] [name = no])。click(function(){

//返回html
target_loadin.html(target_html) ;

//重新加载删除函数
delete_uploaded();

return false;
});

});

返回false;
});
}

//用于处理已删除项目的回调函数。
this.process_delete_uploaded = function(xml){

//追加一个弹出div。
$(document.body).append(< div id = \popup_result \class = \popup \>< / div>);

var popup = $('#popup_result');
var width = 400;
var top = 220;
var scrollTop = $(window).scrollTop();
var scrollLeft = $(window).scrollLeft();
var marginLeft = - +((scrollLeft + width)/ 2);

popup.css({
top:(scrollTop + top)+px,
left:50%,
marginLeft:marginLeft +px ,
width:width +px,
zIndex:11,
display:none
});

//处理结果并加载结果页面并在结果页面显示结果消息。
popup.load(http_root + rp_cms +result.php,{},function(){

//循环显示任何错误消息
$(error, xml).each(function(){
var elementid = $(this).attr('elementid');
var message = $(this).attr('message');
$(#+ elementid +_ label).addClass('error');
$(#+ elementid +_ img).css({visibility:'visible'});
$(。result)。append(< img src ='+ http_root + rp_image_global +attention.png'/>< b>+ message +< / b>< br /> ;);
popup.fadeIn('slow',function(){
closePopup(popup);
});
});
$ b $
$(result,xml).each(function(){

//存储结果节点
var message = $(this).attr('message');
// alert(message);

//追加e结果类中的积极消息。
$(。result)。append(< img src ='+ http_root + rp_image_global +info.png'/>< b>+ message +< / b>< br />);

//通过淡入淡出显示消息
popup.fadeIn('fast',function(){

//将超时设置为1分钟()函数(){
popup.fadeOut(slow,function(){
popup.remove();
});
),1000);

//附加closePopup函数。
closePopup(popup);
});

});
});
}

我想将它转换为插件,以便我可以像这样实例化它,

  $(。delete-uploaded)。delete_uploaded({
target_delete:'.item-uploaded' ,
parent_delete:'.items-uploaded',
wrapper_parent:'。upload'
})

等等,

  $(。delete-listed)。delete_uploaded({ 
target_delete:'.item-listed',
parent_delete:'.items-listed',
wrapper_parent:'。upload'
})


$ b $ p


$ b $ p

谢谢。

编辑:



我的尝试迄今为止都很好...

  //你需要一个匿名函数来包装函数以避免冲突
(function($){

// Attach这个jQuery的新方法
$ .fn.extend({

//这是你写插件名称$ b的地方$ b pluginname:function(options){

//设置默认值,使用逗号分隔设置,例如:
var defaults = {
deleteTarget:'.item '列出',
deleteParent:'.items-listed',
wrapperParent:'.upload',
}

var options = $ .extend(默认值,选项);

return this.click(function(){
var o = options;

var target_delete = $(this).parents(o.deleteTarget); / /要删除的项目,例如保存在li
中的项目var parent_delete = $(this).parents(o.deleteParent); //保存删除项目的父项目,例如ul> li
var wrapper_parent = $(this).parents(o.wrapperParent); //包装父类的包装器,例如div> ul> li
var target_loadin = $(this).parent();
var target_html = $(this).parent()。html();
var path_load = $(this).attr('href');

gif loader。
target_loadin.html('< img src ='+ http_root + rp_image_global + img_loader +'style =float:none;/> loading');
// alert( target_html);

//载入删除表单
target_loadin.lo ad(path_load,function(){

//当yes按钮被触发时。
$(input [type = submit] [name = yes])。click(function(){

//获取表单中的action属性的路径。
var path_post = $(this).parent('form')。attr('action');
// alert(path_post);

//制作一个gif加载器。
target_loadin.html('< div class =ajaxloader>< img src ='+ http_root + rp_image_global + img_loader +'style =float:none;/>正在加载< / div> ');

//发布表单
$ .post(path_post,$(this).serialize(),function(xml){

/ /执行表单输出
process_delete_uploaded(xml);
});

//向上滑动已删除的目标
target_delete.slideUp('fast',函数(){

//完全删除它的div
target_delete.remove();
//alert($('li',parent_delete).length);

//计算有多少物品落后
if($('li',parent_delete).length == 0)
{
$('。 ({
borderBottom:'0px solid#999',
padding:'0px 0px 0px 0px'
});
}

});

返回false;
});
});

返回false;

});

}
});

//将jQuery传递给函数
//以便我们能够使用任何有效的Javascript变量名称
//替换$SIGN。但是,我们坚持$(我喜欢美元符号))
})(jQuery);

我按照这里。它运作良好,即使我不明白为什么我必须使用jquery.extend()...

解决方案

一个不完整的例子,应该让你一路顺风:

  $。fn.delete_uploaded = function(settings){
/ *定义每个设置的默认值:* /
var target_delete = settings.target_delete || .item上传;
var parent_delete = settings.parent_delete || .items上传;
var wrapper_parent = settings.wrapper_parent || .upload;
$ b / *this已经是一个jQuery对象:* /
this.click(function(){...});
};

这里是编写jQuery插件的文档。希望有所帮助! jQueryUI源代码也很有用。



编辑:您不必使用 extend ,但是,根据您的场景使用它可能会更方便。 这里是一个很好的答案,涉及 $。fn.extend


I want to learn to write jquery plugin, so I think it would be easier for me to understand if I learn it by converting my functions into a plugin, such as:

these are my normal functions,

this.delete_uploaded = function(){  

    $(".delete-uploaded").click(function(){

        // remove the popup.
        $('#popup_result').remove();

        // same as: var target_delete = $(this).parent().parent().parent();
        var target_delete = $(this).parents('.item-uploaded'); // the item for deletion, such as item held in li 
        var parent_delete = $(this).parents('.items-uploaded'); // the parent that hold delete item, such as ul > li
        var wrapper_parent = $(this).parents('.upload'); // the wrapper that hold the parent, such as div > ul > li
        var target_loadin = $(this).parent();
        var target_html = $(this).parent().html();
        var path_load = $(this).attr('href');

        // make a gif loader.
        target_loadin.html('<img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading');

        // load the delete form.
        target_loadin.load( path_load, function(){

            // when the yes button is triggered.
            $("input[type=submit][name=yes]").click(function(){

                // get the path from attribute of action in the form.
                var path_post = $(this).parent('form').attr('action');
                //alert(path_post);

                // make a gif loader.
                target_loadin.html('<div class="ajaxloader"><img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading</div>');

                // post the form.
                $.post(path_post, $(this).serialize(), function(xml){

                    // procees the form output.
                    process_delete_uploaded(xml);
                });

                // slide up the deleted target.
                target_delete.slideUp('fast', function() {

                    // remove its divs completely
                    target_delete.remove();
                    //alert($('li',parent_delete).length);

                    // count how many items are left behind         
                    if($('li',parent_delete).length == 0)
                    {
                        $('.binder-row',wrapper_parent).css({
                            borderBottom: '0px solid #999', 
                            padding: '0px 0px 0px 0px'
                        });
                    }

                });

                return false;
            });

            // when the no/cancel button is triggered.
            $("input[type=button][name=no]").click(function(){

                // return the html
                target_loadin.html(target_html);

                // reload the delete function
                delete_uploaded();

                return false;
            });

        });

    return false;
    });
}

// callback function for proccesing the deleted item.
this.process_delete_uploaded = function(xml){

    // append a popup div.
    $(document.body).append("<div id=\"popup_result\" class=\"popup\"></div>");

    var popup = $('#popup_result');
    var width = 400;
    var top = 220;
    var scrollTop = $(window).scrollTop();
    var scrollLeft = $(window).scrollLeft();
    var marginLeft = "-"+ ((scrollLeft + width)/2);

    popup.css({
        top:(scrollTop + top) + "px", 
        left:"50%",
        marginLeft:marginLeft + "px",
        width:width + "px",
        zIndex:"11",
        display:"none"
    });

    // proccess the result and load the result page and display the result messages on the result page.
    popup.load(http_root+rp_cms+"result.php", {}, function(){

        // loop for any error messages.
        $("error", xml).each(function(){
            var elementid = $(this).attr('elementid');
            var message = $(this).attr('message');
            $("#"+elementid+"_label").addClass('error');
            $("#"+elementid+"_img").css({visibility:'visible'});
            $(".result").append("<img src='"+http_root+rp_image_global+"attention.png' /> <b>" + message + "</b> <br />");
            popup.fadeIn('slow', function(){    
                closePopup(popup);
            }); 
        });

        // loop for any positive results.
        $("result", xml).each(function(){

            // store the result node.
            var message = $(this).attr('message');
            //alert(message);

            // append the positive messages in the result class.
            $(".result").append("<img src='"+http_root+rp_image_global+"info.png' /> <b>" + message + "</b> <br />");

            // display the messages by fading them in.
            popup.fadeIn('fast', function(){

                // set the timeout to 1 minute to remove the popup
                setTimeout(function(){
                    popup.fadeOut("slow",function(){
                        popup.remove();
                    }); 
                },1000);    

                // attach closePopup function.
                closePopup(popup);      
            });

        });
    });
}

I want to convert it into a plugin so that I can instantiate it like this,

$(".delete-uploaded").delete_uploaded({
  target_delete: '.item-uploaded', 
  parent_delete: '.items-uploaded',
  wrapper_parent:'.upload'
})

and so on,

 $(".delete-listed").delete_uploaded({
    target_delete: '.item-listed', 
    parent_delete: '.items-listed',
    wrapper_parent:'.upload'
 })

Is it possible?

Thanks.

EDIT:

my attempt so far so good...

// You need an anonymous function to wrap around your function to avoid conflict
(function($){

    // Attach this new method to jQuery
    $.fn.extend({ 

        // This is where you write your plugin's name
        pluginname: function(options) {

            //Set the default values, use comma to separate the settings, example:
            var defaults = {
                deleteTarget:   '.item-listed', 
                deleteParent:   '.items-listed',
                wrapperParent:  '.upload',
            }

            var options =  $.extend(defaults, options);

            return this.click(function(){
                var o = options;

                var target_delete = $(this).parents(o.deleteTarget); // The item for deletion, such as item held in li 
                var parent_delete = $(this).parents(o.deleteParent); // The parent that hold delete item, such as ul > li
                var wrapper_parent = $(this).parents(o.wrapperParent); // The wrapper that hold the parent, such as div > ul > li
                var target_loadin = $(this).parent();
                var target_html = $(this).parent().html();
                var path_load = $(this).attr('href');

                // Make a gif loader.
                target_loadin.html('<img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading');
                //alert(target_html);

                // Load the delete form.
                target_loadin.load( path_load, function(){

                    // When the yes button is triggered.
                    $("input[type=submit][name=yes]").click(function(){

                        // Get the path from attribute of action in the form.
                        var path_post = $(this).parent('form').attr('action');
                        //alert(path_post);

                        // Make a gif loader.
                        target_loadin.html('<div class="ajaxloader"><img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading</div>');

                        // Post the form.
                        $.post(path_post, $(this).serialize(), function(xml){

                            // Procees the form output.
                            process_delete_uploaded(xml);
                        });

                        // Slide up the deleted target.
                        target_delete.slideUp('fast', function() {

                            // Remove its divs completely
                            target_delete.remove();
                            //alert($('li',parent_delete).length);

                            // Count how many items are left behind         
                            if($('li',parent_delete).length == 0)
                            {
                                $('.binder-row',wrapper_parent).css({
                                    borderBottom: '0px solid #999', 
                                    padding: '0px 0px 0px 0px'
                                });
                            }

                        });

                        return false;
                    });
                });

                return false;

            });

        }
    });

//pass jQuery to the function, 
//So that we will able to use any valid Javascript variable name 
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )       
})(jQuery);

I have followed the tutorial from here. it works well even though I don't quite understand why I have to use jquery.extend()...

解决方案

Here's an incomplete example that should get you along your way:

$.fn.delete_uploaded = function(settings) {
    /* Define defaults for each of the settings: */
    var target_delete = settings.target_delete || '.item-uploaded';
    var parent_delete = settings.parent_delete || '.items-uploaded';
    var wrapper_parent = settings.wrapper_parent || '.upload';

    /* "this" is already a jQuery object: */
    this.click(function() { ... });
};

Here's the documentation for writing jQuery plugins. Hope that helps! Also useful is the jQueryUI source code.

Edit: You do not have to use extend, however, it might be more convenient to use depending on your scenario. Here's a good answer that deals with $.fn.extend.

这篇关于jquery插件:将函数转换为插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆