我需要帮助来简化我的 AJAX 代码。我完全是个新手,我确信我的方法是错误的,错误的,错误的。但我不确定如何纠正我的错误并正确执行。
要点:
- 我有很多经验。
- 我正在使用 jQuery、Masonry 和 Infinite Scroll 来像 Pinterest 一样显示它们。
- 每个缩略图下方都有一个链接,用于隐藏缩略图/将其从图库中删除。
- 我已经设法使隐藏功能与下面的代码一起工作。
- 但我的业余 hack 要求每个拇指都有自己的脚本片段,如图所示。
问题:有没有一种方法可以加强这一点,以便一个代码片段可以应用于页面上的所有缩略图?
<div id="gallery-wrapper">
<div class="thumb" id="thumb_75">
<img src="/thumbs/thumb_75.jpg" alt="Thumb 75">
<a href="/url/to/hide_thumb.php" id="hide_75">Delete</a>
</div>
<script>
$('#hide_75').click(function(e){e.preventDefault();
$.post($(this).attr("href"));
$('#thumb_75').hide(500);
});
</script>
</div>
另外:我注意到,当新的缩略图被添加/附加到第一批缩略图(使用无限滚动)时,上述隐藏功能不适用于附加的缩略图 - 仅开始时加载的原始缩略图。
我相当确定我需要“告诉”jQuery 这些新的缩略图已经被添加了,但是由于上面的代码太笨拙了,我不确定如何/从哪里开始。
我的 Infinite Scroll 代码包含在页面的最底部,看起来像这样:
//Infinite scroll
$wall.infinitescroll({
navSelector : 'div.pagination',
nextSelector : 'div.pagination a.more',
itemSelector : '.thumb',
loading: {
msgText: "Loading more thumbs...",
finishedMsg: "That's all folks.",
img: "/graphics/loading.gif"
},
animate : true,
extraScrollPx: 150,
debug: true,
errorCallback: function() {
$('#infscr-loading').animate({opacity: 0},2500);
}
},
function( newElements ) {
var $newElems = $( newElements ).css({ opacity: 0 });
$newElems.imagesLoaded(function(){
///// PRETTY SURE I NEED TO DO SOMETHING HERE TO INFORM jQUERY OF THE NEW ITEMS
$newElems.animate({ opacity: 1 });
$wall.masonry( 'appended', $newElems, true );
}
});
});
谢谢。
最佳答案
尝试以下操作:
// add a listener on the gallery-wrapper. All clicks on links inside the
// wrapper will be caught here. This way, new thumbs which are added later
// are also covered, because you aren't listining on every child but on
// one static container.
$('#gallery-wrapper').on('click', 'a', function (e) {
// prevent default action
e.preventDefault();
// get the current scope, this is the 'a'-element
var $this = $(this);
// post to the url
$.post($this.attr('href'));
// find container of current thumbnail and hide
$this.closest('.thumb').hide(500);
});
关于javascript - 如何修复这个业余的 jQuery/Masonry/Infinite Scroll 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16435601/