javascript - 使用javascript从数组中的HTML页面捕获图像
问题描述
我正在尝试使用 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()
行和最后一行缺少一些右括号。
不确定这是否会使您的代码执行您最终希望它执行的操作,但至少不会导致语法错误。
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, ""));
}
});
推荐阅读
- javascript - 将名称重新格式化为姓氏,名字
- android - 设置可见性消失后无法在 EditText 内输入
- c++ - copyfile_state_get 总是显示 0
- java - 在 Hangman.java 中打印遗漏的字母数组
- hadoop - H20 Hadoop 启动
- string - 当您的函数具有大量输入时,在汇编级别会发生什么
- ruby-on-rails - 检查 bson 数组是否包含字符串 id
- arrays - VBS 使用变量字符串引用数组名称给出类型不匹配 'ubound' 代码:800A000D
- python - Python Pandas 风格
- php - 输出连接表