2013-03-25 30 views
0

我一直試圖在我的網頁上動態生成文本框。我使用我發現的一個示例得到了它的工作,但我遇到了添加到每行的「刪除」按鈕的問題。jQuery動態文本框問題

Firebug在最後一行給了我一個語法錯誤,但我無法弄清楚它爲什麼在抱怨。

這裏是jQuery的功能:

$(document).on('ready', function() { 

    var counter = 2; 

    $("#addButton").click(function() { 
     if(counter>10){ 
      alert("Only 10 learning objectives allowed per page."); 
      return false; 
     } 

     var newTextBoxDiv = $(document.createElement('div')) 
      .attr("id", 'TextBoxDiv' + counter); 
     newTextBoxDiv.after().html('<label>Page Objective ' + counter + ' : </label>' + 
      '<input type="text" name="tbObjective' + counter + 
      '" id="tbObjective' + counter + '" value="" >' + 
      '<input type="button" value="Remove Objective" class="removeObjective">').click(function() { 
       alert('fired'); 
       $(this).remove(); 
      }); 
    }); 
     newTextBoxDiv.appendTo("#TextBoxesGroup"); 
     counter++; 
    }); 

    $("#removeButton").click(function() { 
     alert('fired'); 
     if(counter==1){ 
      alert("No more textbox to remove"); 
      return false; 
     } 
     counter--; 
     $("#TextBoxDiv" + counter).remove(); 
    }); 

    $(".removeObjective").click(function() { 
     alert('fired'); 
     var $id = $(this); 
     $($id).remove(); 
    }); 

}); //Firebug is showing a syntax error here? 
+0

不敢肯定這是否重要,但改變$ id來標識的JavaScript變量不使用$標識符。也失去了按鈕本身on_click,它不需要與jQuery – 2013-03-25 18:11:04

+1

上面張貼是不正確的。用$來預先加載一個jQuery對象來跟蹤它的類型是很常見的約定。將它包含在一個javascript變量名中是合法的。這就是說,在你定義它之後,你不需要在$()中重新包裝它,只需$ id.remove()就可以了。 – 2013-03-25 18:14:05

回答

1

是什麼線20有一組額外的]);其過早關閉了含有準備回調。

此代碼現在是語法正確:

$(document).on('ready', function() { 

    var counter = 2; 

    $("#addButton").click(function() { 
     if(counter>10){ 
      alert("Only 10 learning objectives allowed per page."); 
      return false; 
     } 

     var newTextBoxDiv = $(document.createElement('div')) 
      .attr("id", 'TextBoxDiv' + counter); 
     newTextBoxDiv.after().html('<label>Page Objective ' + counter + ' : </label>' + 
      '<input type="text" name="tbObjective' + counter + 
      '" id="tbObjective' + counter + '" value="" >' + 
      '<input type="button" value="Remove Objective" class="removeObjective">').click(function() { 
       alert('fired'); 
       $(this).remove(); 
      }); 
     newTextBoxDiv.appendTo("#TextBoxesGroup"); 
     counter++; 
    }); 

    $("#removeButton").click(function() { 
     alert('fired'); 
     if(counter==1){ 
      alert("No more textbox to remove"); 
      return false; 
     } 
     counter--; 
     $("#TextBoxDiv" + counter).remove(); 
    }); 

    $(".removeObjective").click(function() { 
     alert('fired'); 
     var $id = $(this); 
     $($id).remove(); 
    }); 

}); 
0

如果計數器的整點是爲了給唯一的ID的文本框,你不需要遞減它。其實我認爲減少它會導致問題。

代替

($this).remove 

使用

$('#TextBoxDiv' + counter).remove();