JavaScript函数重复多次

时间:2017-03-30 15:52:05

标签: javascript jquery

我有两个功能print和callPrint。我第一次点击通话功能打印是对的。 但是当点击呼叫功能打印第二个或第三个然后函数callPrint将被调用2次或3次。 我对攻击文件进行了调试。

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView

    // Tells the gridView to "queue" the following runnable
    gridView.post(new Runnable() {
        @Override
        public void run() {
            onShowTutorial(); // <--- This is where I need to get the firstChild.
        }
    });
}

A JavaScript function is repeated many times

2 个答案:

答案 0 :(得分:0)

问题是因为每次调用load()时,您都会向iframe附加两个新的print()事件处理程序。要解决此问题,请添加一个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);
  }
}

答案 1 :(得分:0)

谢谢&#34; Rory McCrossan&#34;。我在callPrint时添加了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();
}