我有一个动态创建一些元素的模块。由于它们是动态创建的,因此我使用包含动态创建元素的静态元素$('#data-container)
来绑定事件,如下所示:
var $dataContainer = $('#data-container');
var $deleteProject = $('.delete-project');
$dataContainer.on('click', $deleteProject, _deleteProject);
Sooo ....如果我点击的按钮,我无法使用$(this)
获取ID
。上下文是#data-container
,而不是我点击的实际按钮。我还要补充一点,那我该怎么做呢?以下是我更好理解的完整代码:
var $dataContainer = $('#data-container'); // Container holding dynamic elements
var $deleteProject = $('.delete-project'); // Delete buttons for elements
$dataContainer.on('click', $deleteProject, _deleteProject);
function _deleteProject(){
var project = $(this).attr('id'); // Doesn't work
console.log(project);
}
答案 0 :(得分:1)
您可以从event参数中获取ID。试试这个。该事件应始终包含单击的目标。
function _deleteProject(event){
var id = event.target.id;
var project = $(this).attr('id'); // Doesn't work
console.log(project);
}