使用jQuery动态添加文本框 [英] Dynamically add textbox using jquery

查看:100
本文介绍了使用jQuery动态添加文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码有什么问题?只有第一个添加和删除链接有效...

What's wrong with this code ? Only first add and remove link is working...

<html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
 div{
  padding:8px;
 }
</style>

</head>

<body>


<script type="text/javascript">

$(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('<TABLE><TR><TD>' +
'<input type="text" name="textbox' + counter + 
'" id="textbox' + counter + '" value="" ></TD><TD><input type="text" name="textbox' + counter + 
'" id="textbox' + counter + '" value="" ></TD>&nbsp;<TD><a href="#" value="addButton" class="addButton">Add</a>&nbsp;<a href="#" value="removeButton" class="removeButton">Remove</a></TD></TR></TABLE>');

 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);
     });
  });
</script>
</head><body>

<div id='TextBoxesGroup'>
 <div id="TextBoxDiv1">
  <TR><TD><input type='textbox' id='textbox1' ></TD>&nbsp;<TD><input type="text" name="textbox' + counter + 
'" id="textbox' + counter + '" value="" ></TD>&nbsp;<TD><a href="#" value="addButton" class="addButton">Add</a>&nbsp;<a href="#" value="removeButton" class="removeButton">Remove</a></TD></TR>
 </div>
</div>

</body>
</html>

推荐答案

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

When you bind the click() handler, there's only one Add link on the page to bind to. Use live() to capture click events for elements that aren't on the page yet:

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

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

这篇关于使用jQuery动态添加文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆