JavaScript函数会重复多次
我有两个函数print和callPrint。我点击调用函数打印第一次是对的。 但当单击第二次或第三次调用函数打印时,函数调用打印将被调用2次或3次。 我对攻击文件进行了调试JavaScript函数会重复多次,javascript,jquery,Javascript,Jquery,我有两个函数print和callPrint。我点击调用函数打印第一次是对的。 但当单击第二次或第三次调用函数打印时,函数调用打印将被调用2次或3次。 我对攻击文件进行了调试 function print(url) { console.log('print'); var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint'); if ($iframe.attr('src') != u
function print(url) {
console.log('print');
var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint');
if ($iframe.attr('src') != url) {
$.when(
$iframe.attr('src', 'about:blank'),
$iframe.load(function () {
console.log($iframe.prop('contentWindow').document.readyState);
})
).done(function () {
$iframe.attr('src', url);
$iframe.load(function () {
console.log('new');
_this.callPrint(iframeId);
});
});
} else {
console.log('old');
_this.callPrint(iframeId);
}
}
// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
console.log('callPrint');
$('div.wait').hide();
var PDF = document.getElementById(iframeId);
PDF.focus();
PDF.contentWindow.print();
return false;
}
问题是因为每次调用
print()
时,都要将两个新的load()
事件处理程序附加到iframe
。要解决此问题,请添加一个load()
事件处理程序,并从中调用函数。每当您更新元素上的src
属性时,就会触发此操作。试试这个:
var $iframe = $('#iframeprint').load(function() {
// You'll need to make sure the function is in scope of the handler
// There's not enough information in the OP for me to show you how
callPrint('iframeprint');
});
function print(url) {
var _this = this;
if ($iframe.attr('src') != url) {
$iframe.attr('src', url);
} else {
_this.callPrint(iframeId);
}
}
谢谢“Rory McCrossan”。我在调用打印时添加了setTimeout函数,这样打印对话框就会打开。但我现在不能投你的票
var $iframe = $('iframe#iframeprint').load(function () {
// You'll need to make sure the function is in scope of the handler
// There's not enough information in the OP for me to show you how
setTimeout(function () {
callPrint('iframeprint');
}, 100);
});
function print(url) {
if ($iframe.attr('src') != url) {
$iframe.attr('src', url);
} else {
console.log('old');
callPrint('iframeprint');
}
}
// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
$('div.wait').hide();
var PDF = document.getElementById(iframeId);
PDF.focus();
PDF.contentWindow.print();
}
问题是,每次调用
print()
时,您都将一个新的load()
事件附加到iframe
处理程序。