使用jquery动态添加文本框

这段代码出了什么问题? 只有第一个添加和删除链接正在运行…

    div{ padding:8px; }     $(document).ready(function(){ var counter = 2; $(".addButton").click(function () { if(counter>5){ alert("Only 5 textboxes allow"); return false; } var newTextBoxDiv = $(document.createElement('div')) .attr("id", 'TextBoxDiv' + counter); newTextBoxDiv.html(' 
' + 'Add Remove
'); newTextBoxDiv.appendTo("#TextBoxesGroup"); counter++; }); $(".removeButton").click(function () { if(counter==1){ alert("No more textbox to remove"); return false; } counter--; $("#TextBoxDiv" + counter).remove(); }); $("#getButtonValue").click(function () { var msg = ''; for(i=1; i<counter; i++){ msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val(); } alert(msg); }); });
  Add Remove

绑定click()处理程序时,页面上只有一个Add链接要绑定到。 使用live()捕获页面上尚未出现的元素的点击事件:

 $(".addButton").live("click", function () { 

工作演示: http : //jsfiddle.net/u9hvp/

使用live()已被折旧,并且自Andy E发布以来已被删除。 现在使用以下语法支持相同的function:

$(document).on(“click”,“。removeButton”,function(){

你只需在你的文件夹中添加这个文件就可以了!

jQuery的1.3.2.min.js