javascript - 如何在正确的上下文中将函数传递给单击处理程序?

标签 javascript jquery function object onclick

我必须从按钮的 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 保存在您创建的 divdata 属性中,当点击事件发生时可以读取它。试试这个:

// 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/

相关文章:

javascript - 我怎样才能让一条消息位于 html 之上?

javascript - 在页面加载时滚动到 div

javascript - 插入符号索引位置跨浏览器?

javascript - 一旦我在特定部分滚动,使某个 id 消失?

javascript - 如何防止在页面加载时执行JavaScript函数?

jQuery 和闭包

c++ - 如何将cpp文件中的静态函数暴露给其他文件

javascript - 获取元素 id,然后在 getElmentByID 中使用它来触发单击函数

javascript - 按 "Levenshtein Distance"对数组进行排序,在 Javascript 中性能最佳

javascript - 当字符串中存在多个空格时,字数统计不正确