2013-03-08 65 views
0

如何将此代码转换为一个函数,我需要将其绑定到div ID并传入nameid参数以用于输入?从代码块创建jQuery函数

  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); 
      }); 
+0

'var newfun = $(function myfun(name,id){... your code});'' – SRy 2013-03-08 17:16:45

回答

1

你的意思是你想一个jQuery的原型功能,东西那个行为像$('div').doSomething(name, id);?在这种情况下,它是:

$.fn.doSomething = function (name, id) {...}; 
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); 
    }); 
}