我已经写了一些JS代码,它过滤了所有大于指定大小的图像。筛选后的DOM连接到单击事件。
var largeImages = allImages.filter(function(){
return ($(this).width() > 70) || ($(this).height() > 70)
}); 但是现在我也用AJAX向DOM添加了一些图片。这些图片具有通过该过滤器的大小,但目前没有被过滤,因为它们是在DOM过滤后添加的。
现在我有两个问题:
更新:我没有机会绑定到添加照片的事件。我正在开发一个Chrome扩展程序,它提供了一些处理照片的选项。
发布于 2013-12-01 21:01:13
如果您需要监视dom更改以重新运行您的筛选器,并且只以chrome为目标(这是一个chrome扩展),那么您可以使用DOM突变观察者。
然后,当dom发生变化时,您可以重新运行过滤器。就像这样:
var observer = new MutationObserver(function(){
// run your filter here
});
observer.observe(document);发布于 2013-12-01 20:30:20
您应该绑定添加新映像的事件(即AJAX调用的回调函数)。
发布于 2013-12-01 20:46:09
您可以使用一个活动的nodeList,然后访问该变量;例如:
var images = document.getElementsByTagName('img');将持续跟踪图像,包括添加到文档中的新图像。当然,这种方法意味着每次向页面添加另一个nodeList时都必须过滤该img。虽然这是可能的,但其推论是,您可以简单地重新选择相关的元素,就像将它们添加到页面中一样。然而,有一种办法:
var images = document.getElementsByTagName('img');
$('#addImage').click(function(e){
e.preventDefault();
$('<img />', {
'src' : 'http://placekitten.com/150/150/',
'height' : '150px',
'width' : '150px'
}).insertAfter('#count');
$('#count').text(function(){
// using Array.prototype.filter() to filter the array:
return [].filter.call(images, function(a){
return a.naturalWidth > 70;
}).length;
});
});但是,可以通过以下方法实现同样的效果(只需在添加后重新选择img元素):
$('#addImage').click(function(e){
e.preventDefault();
$('<img />', {
'src' : 'http://placekitten.com/150/150/',
'height' : '150px',
'width' : '150px'
}).insertAfter('#count');
$('#count').text(function(){
return $('img').filter(function(){
return this.naturalWidth > 70;
}).length;
});
});参考文献:
https://stackoverflow.com/questions/20316850
复制相似问题