【发布时间】:2019-09-22 22:02:24
【问题描述】:
我正在尝试使用 Javascript 捕获 HTML 页面中的所有图像。我发现了这个类似的问题,最好的答案非常详细地给出了该问题的解决方案: Detect all images with Javascript in an html page
我的问题是,即使我直接复制/粘贴到 Firefox 控制台中,我也无法让最佳答案中显示的代码正常运行。我怀疑答案是直截了当的,虽然这让我摸不着头脑 - 有人能帮忙吗?
这段代码给了我错误“SyntaxError: missing ) after argument list”...
var elements = document.body.getElementsByTagName("*");
Array.prototype.forEach.call( elements, function ( el ) {
var style = window.getComputedStyle( el, false );
if ( style.backgroundImage != "none" ) {
images.push( style.backgroundImage.slice( 4, -1 ).replace(/['"]/g, "")
}
}
似乎包括上述内容的完整解决方案似乎也给出了相同的错误...
var images = [],
bg_images = [],
image_parents = [];
document.addEventListener('DOMContentLoaded', function () {
var body = document.body;
var elements = document.body.getElementsByTagName("*");
/* When the DOM is ready find all the images and background images
initially loaded */
Array.prototype.forEach.call( elements, function ( el ) {
var style = window.getComputedStyle( el, false );
if ( el.tagName === "IMG" ) {
images.push( el.src ); // save image src
image_parents.push( el.parentNode ); // save image parent
} else if ( style.backgroundImage != "none" ) {
bg_images.push( style.backgroundImage.slice( 4, -1 ).replace(/['"]/g, "") // save background image url
}
}
/* MutationObserver callback to add images when the body changes */
var callback = function( mutationsList, observer ){
for( var mutation of mutationsList ) {
if ( mutation.type == 'childList' ) {
Array.prototype.forEach.call( mutation.target.children, function ( child ) {
var style = child.currentStyle || window.getComputedStyle(child, false);
if ( child.tagName === "IMG" ) {
images.push( child.src ); // save image src
image_parents.push( child.parentNode ); // save image parent
} else if ( style.backgroundImage != "none" ) {
bg_images.push( style.backgroundImage.slice( 4, -1 ).replace(/['"]/g, "") // save background image url
}
} );
}
}
}
var observer = new MutationObserver( callback );
var config = { characterData: true,
attributes: false,
childList: true,
subtree: true };
observer.observe( body, config );
});
谢谢。
【问题讨论】:
-
许多括号未对齐且未闭合,例如
images.push(中的(。您从中复制错误代码的答案不是很好 -
感谢您的坦率反馈,@CertainPerformance!仅仅是语法错误导致您说代码很糟糕,还是您认为可以改进其一般功能的某些方面?
-
如果代码在语法错误得到修复后可以正常工作,我想这已经足够了,尽管有很多事情需要改进,只是在一般情况下代码质量。 (例如,最好使用现代语法,将两个相同的
forEach块抽象为一个函数,continue而不是一个大的if块,仅在将要使用它们的上下文中声明变量,等)简洁、重构、现代的代码减少了错误和拼写错误的表面积
标签: javascript html css image