技术实践
关于闭包修复一个问题
测试反馈ie有问题,自己仔细已检查确实有问题,首选可以看到在使用了for循环中使用了let变量,由于是pdf.js,没有经过打包转义es6

产品里有这样一个功能

需要在pdf.js源码的html加一个菜单,切换使用浏览器内置打开
好的,开始写代码
js
var iframes = window.parent.document.getElementsByTagName('iframe')
for (let i = 0; i < iframes.length; i++) {
console.log(iframes[i])
if(iframes[i].contentWindow.document.getElementById('presentationLoad')){
iframes[i].contentWindow.document.getElementById('presentationLoad').onclick = function (){
var iframe = iframes[i];
if(iframe){
var url = iframe.getAttribute('src').split('viewer.html?file=')[1];
window.open(location.origin + url,'_blank')
console.log(url)
}
}
}
}
此段代码在谷歌火狐现代浏览器没有任何问题,自己没有测试ie,发布到内网,等待验收
测试反馈ie有问题,自己仔细已检查确实有问题,首选可以看到在使用了for循环中使用了let变量,由于是pdf.js,没有经过打包转义es6 。是es5的代码,需要在IE浏览器中,需要用到闭包解决次问题,我们在把代码改造下,就更加完善了
js
(function (){
var iframes = window.parent.document.getElementsByTagName('iframe')
for (var i = 0; i < iframes.length; i++) {
(function (i){
if(iframes[i].contentWindow.document.getElementById('presentationLoad')){
iframes[i].contentWindow.document.getElementById('presentationLoad').onclick = function (){
var iframe = iframes[i];
if(iframe){
var url = iframe.getAttribute('src').split('viewer.html?file=')[1];
window.open(location.origin + url,'_blank')
console.log(url)
}
}
}
})(i)
}
})()