带下划线模板的另一个函数jQuery内部调用的事件不起作用 [英] events called from inside another function jQuery with underscore template doesn't work

查看:128
本文介绍了带下划线模板的另一个函数jQuery内部调用的事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,用于将元素添加到列表中,我想让事件在与此列表进行交互时运行,例如点击.如果使用文档对象执行此操作,则效果很好,但是如果我将jQuery与下划线模板一起使用,则该元素已成功添加,但不会触发事件.

I have a function which i used to add elements to a list, I want to have events run on interaction with this list, e.g. click. If I do it using the document object it works well however if I use jQuery with underscore templates the element is successfully appended but the events will not trigger.

var addElement = function(parentElement){
    //would work
    this.thisElement = document.createElement('li');
    parentElement.appendChild(thisElement);
    $(this.thisElement).click(function(event){
        alert('working');
    });

    //doensn't work
    this.template = _.template($('#fileListEntity').html());
    var li = this.template();
    $(parentElement).append(li);
    $(li).click(function(e) {
        alert('notWorking');
    });
};

推荐答案

因此,在megakorre的帮助下,这就是答案.

so with the help of megakorre this is the answer.

this.template = _.template($('#fileListEntity').html());
var li = $(this.template({name:doc.name}));
$(parentElement).append(li);

li.click(function(e) {
   alert('click');
});

这篇关于带下划线模板的另一个函数jQuery内部调用的事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆