问题
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