Click event doesn’t fire after browser resize

你离开我真会死。 提交于 2019-12-23 04:17:11

问题


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

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