简体   繁体   English

浏览器调整大小后点击事件不会触发

[英]Click event doesn’t fire after browser resize

I'm currently using slick , a carousel.我目前正在使用slick ,一个轮播。 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).当浏览器的大小调整到低于某个阈值时,我将轮播设置为不unslick (意味着它不再是轮播,并且每个轮播面板都静态显示在另一个之上)。 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.但是,我还有一个.click函数,当单击轮播中的元素时会调用该函数。 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. .click函数在页面的初始加载时起作用,但如果页面被调整大小,则不再起作用。 Any ideas?有任何想法吗?

The plugin may be replacing the HTML which causes it to lose the event handlers assigned to those DOM elements.该插件可能正在替换 HTML,这导致它丢失分配给这些 DOM 元素的事件处理程序。 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'.这样做是让文档(永远不会被删除)处理事件并检查事件的实际目标是否与选择器匹配,在本例中为“#linkInCarousel”。 This way, even if the element is added after page load the handler will fire properly.这样,即使在页面加载后添加元素,处理程序也会正确触发。

In general it can be beneficial to use delegation when dealing with a list of elements, so you're only adding one event handler as opposed to creating the handlers for every element.通常,在处理元素列表时使用委托是有益的,因此您只需添加一个事件处理程序,而不是为每个元素创建处理程序。 Read more about it here.在此处阅读更多相关信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM