从代码块创建jQuery函数

时间:2013-03-08 17:13:10

标签: jquery function

如何将此代码转换为一个函数,我需要做的就是将其绑定到div id,并为输入传入nameid参数?

            var startingNo = 3;
            var $node = "";
            for(varCount=0;varCount<=startingNo;varCount++){
                var displayCount = varCount+1;
                $node += '<p><input type="text" name="duties'+displayCount+'" id="duties'+displayCount+'"><span class="removeVar">Remove Variable</span></p>';
            }

            //add them to the DOM
            $('#duties').prepend($node);

            //remove a textfield
            $('#duties').on('click', '.removeVar', function(){
               $(this).parent().remove();
               varCount--;
            });

            //add a new node
            $('#addVar').on('click', function(){
            varCount++;
            $node = '<p><input type="text" name="duties'+varCount+'" id="duties'+varCount+'"><span class="removeVar">Remove Variable</span></p>';
            $(this).parent().before($node);
            });

2 个答案:

答案 0 :(得分:1)

你的意思是你想要一个jQuery原型函数,它的行为类似于$('div').doSomething(name, id);吗?在那种情况下,它是:

$.fn.doSomething = function (name, id) {...};

答案 1 :(得分:0)

我不知道我是否正确使用它,但它只是在标签创建和jquery选择器中连接:

function myFunction(name, id) {
    var startingNo = 3;
    var $node = "";
    for(varCount = 0; varCount <= startingNo; varCount++) {
        var displayCount = varCount + 1;
        $node + = '<p><input type="text" name="' + name + displayCount + '" id="' + id + displayCount + '"><span class="removeVar">Remove Variable</span></p>';
    }

    //add them to the DOM
    $('#' + id).prepend($node);

    //remove a textfield
    $('#' + id).on('click', '.removeVar', function(){
       $(this).parent().remove();
       varCount--;
    });

    //add a new node
    $('#addVar').on('click', function(){
        varCount++;
        $node = '<p><input type="text" name="' + name + varCount + '" id="' + id + varCount + '"><span class="removeVar">Remove Variable</span></p>';
        $(this).parent().before($node);
    });
}
相关问题