Javascript: closures? eventlistener won't add
I seem to have a problem, and I suspect it's a problem with closures. I got 3 buttons, and when I run this code only the last button gets an eventlistener. This is why I suspect a closures problem. I tried all sorts of things as create other functions but the didn't help me. In the function addListeners i have 3 console.logs with information and they display the RIGHT information. So in addeventlisteners I have the right DIV, with the right information but it doesn't add a listener. Could anyone help me out here? I have no idea what I'm doing wrong.
function CheckAiringShows(slug,lastwatched,Length) {
var nmb = lastwatched.number;
var nxnmb = nmb +1;
$.ajax({
type: "GET",
url: "https://api-v2launch.trakt.tv/calendars/all/shows/"+strDate+"/30",
headers: {
"Content-Type": "application/json",
"trakt-api-version": "2",
"trakt-api-key": "a16246673f04042fca0fbc80eddd2b8b742524f62deaf11a6d0daf97f053005f"
},
success : function(response)
{
response.forEach(function (object, index) {
if(slug == object.show.ids.slug){
var airdate = new Date(object.first_aired).format("dddd, mmmm dS 'at' HH:MM:ss");
var nextnumber = "s"+object.episode.season+"e"+object.episode.number;
document.getElementsByClassName("airingshow")[0].innerHTML += "<label for='test'>"+object.show.title+": "+nextnumber+" "+airdate+"</label><input type='submit' class='calendar' id='"+object.episode.ids.trakt+"' value='Add to calendar!'/>";
var calend = document.getElementById(object.episode.ids.trakt);
addListeners(calend,object,Length);
}
});
}
});
}
function addListeners(item,object,length){
console.log(item);
console.log(object);
console.log(length);
// this line didn't work out at all, nothing got an eventlistener this way.
// return function(){item.addEventListener('click', function(){makeApiCall(object,length)})};
item.addEventListener('click', function(){makeApiCall(object,length)});
}
It's because you are replacing the innerHTML
in every iteration, effectively destroying previously created DOM elements and replacing them.
Here's a few solutions:
innerHTML
and attach handlers. document.createElement(...)
, container.appendChild(...)
). Event delegation is usually more simple if the content of a container is dynamic, because you do not have to worry about adding handlers on newly added elements.
$('#dynamic-container')
.on('click', 'button', function () {
alert('You clicked on a button!');
})
//cliking dynamically added button will also work
.append('<button>dynamic button</button>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dynamic-container">
<button>static button</button>
</div>
链接地址: http://www.djcxy.com/p/1504.html
上一篇: Node.js与.Net性能