我正在使用表格行创建一个动态输入字段
var i = 1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" id ="lable" name="lable" ></tr>');
});
$('#lable').click(function(){
alert('called');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="dynamic_field">
<td colspan="2">
<button type="button" name="add" id="add" class="btn btn-success">Add Lable</button>
</td>
</table>
但没有发出警报
答案 0 :(得分:0)
由于动态创建了输入,因此应使用event delegation。这意味着使用
$(document).on("click", '#lable', function(){
代替
$('#lable').click(function(){
请注意,HTML中不能有重复的id
属性。因此,请改用类(.lable
)。
var i = 1
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" class="lable" name="lable"></tr>');
});
$(document).on("click", '.lable', function(){
alert('called');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="dynamic_field">
<tr>
<td colspan="2">
<button type="button" name="add" id="add" class="btn btn-success">Add Lable</button>
</td>
</tr>
</table>