【问题标题】:Dynamically add textbox using jquery使用jquery动态添加文本框
【发布时间】:2013-09-30 12:58:04
【问题描述】:

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

<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>

【问题讨论】:

    标签: jquery


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      在 Andy E 的帖子发布后,live() 的使用已被贬低并删除。现在使用以下语法支持相同的功能:

      $(document).on("click", ".removeButton", function () {

      【讨论】:

        【解决方案3】:

        您只需将此文件添加到您的文件夹中,它就可以正常工作...!

        jquery-1.3.2.min.js

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多