繁体   English   中英

jQuery无法从动态创建的字段获取输入值

[英]JQuery can't get input value from dynamically created field

当基于输入字段类(.inputclass)方法键入内容时,从静态字段接收值,但是一旦动态添加字段,它就无法获取该值。

下面的示例代码,请帮助。

 $(function(){ $(document).ready(function(){ $(".inputclass").keyup(function() { alert($(this).val()); }); }); }); 
 <script src="http://code.jquery.com/jquery-1.12.4.js"></script> <form> <table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable"> <tr> <td>Field 1</td> <td><input type="text" class="inputclass" /></td> </tr> <script> var counter =1; $(function(){ $('#addNew').click(function(){ counter += 1; $('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>'); }); }); </script> </table><br/> <input type="button" id="addNew" value=" &plusmn; Add New Field"/> </form> 

这是因为当您分配事件处理程序时,它当时仅分配给了现有元素。

委托给文档

$(document).on('keyup', '.inputclass', function(){
   alert($(this).val())
});

当您委托给父项或文档时,您将使用冒泡的事件,因此,是否存在动态元素并不重要。

 $(function(){ $(document).ready(function(){ $(document).on('keyup', '.inputclass', function(){ alert($(this).val()); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://code.jquery.com/jquery-1.12.4.js"></script> <form> <table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable"> <tr> <td>Field 1</td> <td><input type="text" class="inputclass" /></td> </tr> <script> var counter =1; $(function(){ $('#addNew').click(function(){ counter += 1; $('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>'); }); }); </script> </table><br/> <input type="button" id="addNew" value=" &plusmn; Add New Field"/> </form> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM