如何使这个jquery更易于重用

how to make this jquery more reusable?

本文关键字:易于重 jquery 何使这      更新时间:2023-09-26

我希望能够通过"骑手"或其他东西,并添加/删除做同样的事情,但对于其他项目以外的骑手,如子帐户。

$(function(){
    var template = $('#riders-div .rider-new:first').clone(),
        ridersCount = 0;
    var addRider = function(){
        ridersCount++;
        var rider = template.clone().removeClass("dontshow").find(':input').each(function(){
            var newId = this.id.replace('-', 's['+ ridersCount + '][') + ']';
            $(this).prev().attr('for', newId); // update label for (assume prev sib is label)
            this.name = this.id = newId; // update id and name (assume the same)
        }).end() // back to .rider
        .appendTo('#rider-exist'); // add to container
        $('#rider-message').html('').removeClass("ui-state-highlight").removeClass("ui-state-error");
    };
    $('#addButton').click(addRider()); // attach event
$("#removeButton").click(function () {
  $('#riders-div .rider-new:last').remove();
$('#rider-message').html('').removeClass("ui-state-highlight").removeClass("ui-state-error");
     });
});
https://gist.github.com/1081078

您将需要从这段代码中创建一个插件。方法是,当你需要更多的功能,添加选项的插件。我启动了下面的插件。此外,替换元素id(等)的代码需要更加通用。下面我添加了一个正则表达式来替换元素id中的数字。

在必要的地方添加回调以执行特定的实现操作/UI调整。因此,在上面的示例中,添加代码以在after回调中重置消息html ($('#rider-message').html(''))。

after: function(i){
    $('#rider-message').html(''); //...
}

等等

$.fn.cloneForm = function(options){
    var self = this, count = 0, 
        opts = $.extend({}, {
            after: function(){}, 
            template:'', 
            prependTo: '', 
            on: 'click'
        }, options),
        template = $(opts.template).clone(); // unmodified clone
    self.bind(opts.on + '.cloneForm', function(){
        count++;
        template.clone().find(':input').each(function(){
            var newId = this.id.replace(/[0-9]/i, count) // replace number
            $(this).prev().attr('for', newId);           // update label for
            this.name = this.id = newId;                 // update id and name (assume the same)
        }).end().prependTo(opts.prependTo);
        opts.after.call(self, count);                    // run callback
    });
}

用法:

$('#addButton').cloneForm({ 
    template: '#riders-div .rider-new:first',
    prependTo: '#riders-div',
    after: function(){ console.log('im done'); }
});

似乎您正在为这个"Rider"模块定义某种管理系统(我不知道,只是我所看到的)。一开始我改进这段代码的方法是使用一些OO js。从这里开始,当需要使其更泛型时(例如更改类名),您可以将这些选择器作为构造函数的参数。它还有一个好处,那就是使代码更容易进行单元测试!

如果你想要一些具体的代码示例,我会张贴一些东西,只是让我知道。