避免jquery函数的重复代码

Avoiding duplication of code for jquery function

本文关键字:代码 jquery 函数 避免      更新时间:2023-09-26

我有这个脚本(我的第一个),我有一点帮助开发:http://jsfiddle.net/spadez/AYUmk/2/

var addButton =$("#add"),
    newResp = $("#resp_input"),
    respTextArea = $("#responsibilities"),
    respList = $("#resp");
//
function Responsibility(text){
    this.text=text;
}
var responsibilities = []; 
function render(){
    respList.html("");
    $.each(responsibilities,function(i,responsibility){
        var el = renderResponsibility(responsibilities[i],function(){
            responsibilities.splice(i,1);//remove the element
            render();//re-render
        });
        respList.append(el);
    });
    respTextArea.text(responsibilities.map(function(elem){
       return elem.text;//get the text. 
    }).join("'n"));
}
addButton.click(function(e){
    var resp = new Responsibility(newResp.val());
    responsibilities.push(resp);
    render();
    newResp.val("");
});
function renderResponsibility(rep,deleteClick){
    var el = $("<li>");
    var rem = $("<a>Remove</a>").click(deleteClick);
    var cont = $("<span>").text(rep.text+" ");
    return el.append(cont).append(rem);
}

使用顶部框,你可以添加责任到文本区域输入框中,并单击添加。这对于我的第一个框完美地工作,但我需要这为三个不同的框工作,现在我有点卡住了如何将这个函数应用到所有三个实例"责任,测试,test2",而不是简单地复制代码三次和改变变量。

我相信这种事情一定会经常发生,但我不确定是否可以避免。希望有javascript经验的人能给我一些启发。

你可以使用javascript的作用域:

function Responsibility(text){
    /* .... */
}
function setUp(addButton, newResp, respTextArea, respList) {

    var responsibilities = []; 
    function render(){
        /* ..... */
    }
    addButton.click(function(e){
        /* ..... */
    });
    function renderResponsibility(rep,deleteClick){
        /* ..... */
    }
}

然后对于每个组,您可以调用:

setUp($("#add"), $("#resp_input"), $("#responsibilities"), $("#resp") );

对于每个字段,您肯定需要有不同的id,如#add1, #add2…或者您也可以将这些分组为例如.group1类的div,并使用class代替id,如.add, .resp_input,然后您甚至可以减少需要传递给设置的参数数量到一个参数(仅传递容器)

我修改了你的代码来做你想做的。

现场演示http://jsfiddle.net/AYUmk/5/


技巧是使您的responsibilities数组成为一个多维数组,为每个项目(在本例中为3个项目)保存一个数组。

var responsibilities = [new Array(),new Array(),new Array()]; 

然后,我更新了添加按钮,使其CLASS为add而不是ID为add。无论如何,都不应该有多个具有相同ID的元素。此外,我还向按钮添加了几个数据项。这些数据项告诉jQuery使用哪个数组项、查找哪个文本框、添加到哪个列表以及添加到哪个文本框。

<input type="button" value="Add" class="add" data-destination='responsibilities' data-source='resp_input' data-list='resp' data-index="0">
...
<input type="button" value="Add" class="add" data-destination='test' data-source='tst_input' data-list='tst' data-index="1">
...
<input type="button" value="Add" class="add" data-destination='test2' data-source='tst2_input' data-list='tst2' data-index="2">

然后它只是一个问题,改变你的click()render()函数来处理数据和多维数组

function render(list, textarea, index){
    list.html("");
    $.each(responsibilities[index],function(i,responsibility){
        var el = renderResponsibility(responsibilities[index][i],function(){
            responsibilities[index].splice(i,1);//remove the element
            render();//re-render
        });
        list.append(el);
    });
    textarea.text(responsibilities[index].map(function(elem){
       return elem.text;//get the text. 
    }).join("'n"));
}
$('.add').click(function(e){
    var source = $('#' + $(this).data('source') ).val();
    var index = parseInt($(this).data('index'));
    var list = $('#' + $(this).data('list') );
    var dest = $('#' + $(this).data('destination') );
    var resp = new Responsibility(source);    
    responsibilities[index].push(resp);
    render(list, dest, index);
    newResp.val("");
});

注意:我没有得到移除工作,如果你需要帮助,请告诉我,一旦我到达我的办公室,我会帮助

我会尝试这样做> http://jsfiddle.net/AYUmk/4/

我将按类而不是按id访问项

$(".class").find("...");

你只需要外包责任= [];然后它就完美地工作了……

但是我不会为你做所有的工作。