This question already has an answer here:
这个问题在这里已有答案:
- Event binding on dynamically created elements? 23 answers
动态创建元素的事件绑定? 23个答案
I am generating HTML dynamically through javascript and have 2 glyphs enclosed within a table cell. The pencil glyph responds correctly however my code for the delete does not and I am not sure why.
我通过javascript动态生成HTML,并在表格单元格中包含2个字形。铅笔字形响应正确,但我删除的代码没有,我不知道为什么。
This is the rendered HTML
这是呈现的HTML
<span id="edit-dp" class="glyphicon glyphicon-pencil" data-action-url="/Settings/GetDatapoint" data-id="3"></span>
<span id="delete-dp" class="glyphicon glyphicon-trash" data-id="3"></span>
and here is my javascript code to tie the event up to the element.
这是我的javascript代码将事件绑定到元素。
$(document).ready(function(){
$('#delete-dp').click(function (event) {
alert('pressed');
//add the datapoint ID to the array to be serialised to JSON and then stored in a html hidden field
deletedDatapoints.push($(this).data('id'));
});
})
2 个解决方案
#1
2
Use .on()
.
$(document).ready(function(){
$(document).on('click', '#delete-dp', function (event) {
alert('pressed');
//add the datapoint ID to the array to be serialised to JSON and then stored in a html hidden field
deletedDatapoints.push($(this).data('id'));
});
});
You could scope it to the closest parent that is not dynamically generated to be more efficient than document
.
您可以将其范围限定为最近的父级,该父级不是动态生成的,而是比文档更高效。
#2
0
To handle dynamicly added events use
要处理动态添加的事件,请使用
$('#delete-dp').on('click',function(event){
//do your stuff
});
#1
2
Use .on()
.
$(document).ready(function(){
$(document).on('click', '#delete-dp', function (event) {
alert('pressed');
//add the datapoint ID to the array to be serialised to JSON and then stored in a html hidden field
deletedDatapoints.push($(this).data('id'));
});
});
You could scope it to the closest parent that is not dynamically generated to be more efficient than document
.
您可以将其范围限定为最近的父级,该父级不是动态生成的,而是比文档更高效。
#2
0
To handle dynamicly added events use
要处理动态添加的事件,请使用
$('#delete-dp').on('click',function(event){
//do your stuff
});