2013-03-08 72 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); 
    }); 
}