events called from inside another function jQuery with underscore template doesn't work

狂风中的少年 提交于 2019-12-25 03:58:27

问题


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');
    });
};

回答1:


are you shore that template() returns a element. if it returns a string (witch most template system do) that click event wont work.

also there's syntactic errors with not closing the click method.




回答2:


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');
});


来源:https://stackoverflow.com/questions/7521731/events-called-from-inside-another-function-jquery-with-underscore-template-doesn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!