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

时间:2017-06-07 11:49:41

标签: javascript jquery html

当keyup基于输入字段类(.inputclass)方法从静态字段接收值,但是一旦动态添加字段,它就不会得到该值。

示例代码下方,请帮助。



<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>
&#13;
{{1}}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:6)

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

Delegate to the document

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

当您委托父母或文档时,您正在使用冒泡的事件,因此如果有动态元素则无关紧要。

答案 1 :(得分:0)

&#13;
&#13;
$(function(){
	$(document).ready(function(){
    $(document).on('keyup', '.inputclass', function(){
					alert($(this).val());
		});
	});
});
&#13;
<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>
&#13;
&#13;
&#13;