infinite scroll javascript already fired

断了今生、忘了曾经 提交于 2019-11-28 12:40:04

问题


I have a site which loads items and uses the jquery infinite scroll plug in to load more items as a user scrolls.

When a user hovers over an item, more small divs are shown over the item. Simple. Which divs are shown on hover depends on which page a user is on, therefore they are dependant on knowing which page they are on. I use a simple variable to sort that out.

I use the following js to decide which divs are shown. eg from homepage

<script>
  $(".list_item_image").mouseenter(function () {
    $(this).children(".gl_view2").show();
    $(this).children(".gl_relist").show();
  });
  $('.list_item_image').mouseleave(function() {
    $(this).children(".gl_view2").hide();
    $(this).children(".gl_relist").hide();
  });
</script>

The divs (gl_view2 & gl_relist) are initially loaded but with display:none;

Now, this js is loaded into the footer to ensure its after the divs in question.

Lets say I have infinite scroll set to update 15 items at a time

This all works perfectly (meaning on mouseenter the divs which should be shown/overlaid, are shown) for the first 15 items, but after that the items load but the mouseenter simply does not work anymore. I'm guessing this is because the js has loaded and when the next items are loaded onto the page the js doesn't have any effect.

To load the next items with infinite-scroll I am using:

<nav id="page_nav"><a href="/pages/infinScrollGather.html?page_offset=2&currentpage=homepage"></a></na‌​v>

I've also tried loading the js in after each item but still only works for the first 15.

I have also tried but this didn't work at all:

$("body").on("mouseenter", ".list_item_image", function () {
...
});

$("body").on("mouseleave", ".list_item_image", function () {
...
});

Has anyone come across anything like this before? Any ideas for a fix?


回答1:


you should use event delegation with on() method like so

$("body").on("mouseenter", ".list_item_image", function () {
  ...
});

$("body").on("mouseleave", ".list_item_image", function () {
  ...
});

this will attach your handlers also on newer elements injected later on the DOM via ajax

only if you are using an older version of jQuery use delegate(), on() otherwise




回答2:


Fixed (I hope so anyway)

It seems the js was missing being wrapped in: $(document).ready(function(){ ... });

Thanks for all help.



来源:https://stackoverflow.com/questions/12139508/infinite-scroll-javascript-already-fired

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