问题
I’m currently using slick, a carousel. When the browser is resized below a certain threshold, I have the carousel set to unslick
(meaning it stops being a carousel and each carousel panel is displayed statically one on top of another). The setting is this:
responsive:[{
breakpoint: 992,
settings: "unslick"
}]
It works great. However, I also have a .click
function that’s called when an element in the carousel is clicked on. Something like:
$(document).ready(function(){
$('#linkInCarousel').click(function(){
console.log('success');
});
}
The .click
function works on initial loading of the page, but if the page is resized, it no longer does. Any ideas?
回答1:
The plugin may be replacing the HTML which causes it to lose the event handlers assigned to those DOM elements. Instead, try delegating the events to the document, like this:
$(document).ready(function(){
$(document).on('click', '#linkInCarousel', function(){
console.log('success');
});
};
What this does is lets the document (which never gets removed) handle the event and checks to see if the actual target of the event matches the selector, in this case '#linkInCarousel'. This way, even if the element is added after page load the handler will fire properly.
In general you should always try to use delegation so you're only adding one event handler per functionality, as opposed to creating the handlers for every element. Read more about it here.
来源:https://stackoverflow.com/questions/32041339/click-event-doesn-t-fire-after-browser-resize