我必须从按钮的 onlick
属性中的函数获取参数值,但是函数 (this.getListItemId(itemId)
) 使用此参数不在按钮所在的上下文中。该按钮位于子函数内
(this.renderVideoListTemplate()
) 位于父函数 (getVideoListItems()
) 内。我想在 onclick 事件 (this.getListItemId()
) 上调用的函数位于按钮 (this.renderVideoListTemplate()
) 函数所在的位置之外,所以它说函数 (this.getListItemId(itemId)
) 不存在。
var getVideoListItems = function() {
var self = this;
this.renderVideoListTemplate = function(result) {
for(let i=0; i < result.length; i++){
====>>> var listItems ="<div class='Button fecharVideo' onclick='"+self.getListItemId(result[i].ID)+"'>"+
"<span class='Button'>Excluir Vídeo</span>"+
"</div>";
$("#video-list-container").append(listItems);
};
};
this.deleteListItem = function(webUrl, listName, itemId, success, failure) {
self.getDataByItemId(webUrl,listName,itemId,function(item){
$.ajax({
url: item.__metadata.uri,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-Http-Method": "DELETE",
"If-Match": item.__metadata.etag
},
success: function (data) {
success();
},
error: function (data) {
failure(data.responseJSON.error);
}
});
},
function (error) {
failure(error);
});
};
this.getListItemId = function(itemId){
self.deleteListItem(webUrl, listName, itemId)
};
return this.init();
}
最佳答案
您不能在 onclick
属性的字符串值内分配函数引用。
您可以通过使用委托(delegate)事件处理程序来避免该问题并改进逻辑。您可以将 result[i].ID
保存在您创建的 div
的 data
属性中,当点击事件发生时可以读取它。试试这个:
// in your object:
this.renderVideoListTemplate = function(result) {
var divs = result.map(function() {
return `<div class="Button fecharVideo" data-id="${this.ID}"><span class="Button">Excluir Vídeo</span></div>`
});
$("#video-list-container").append(divs);
};
// somewhere else in your codebase:
$('#video-list-container').on('click', '.fecharVideo', function(e) {
e.preventDefault();
yourObjectReferece.getListItemId($(this).data('id'));
})
另请注意使用 map()
构建一个字符串数组以附加到 #video-list-container
元素一次,而不是在每次迭代中。
关于javascript - 如何在正确的上下文中将函数传递给单击处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55831081/