关闭时在弹出窗口中垃圾回收JavaScript

时间:2019-05-01 08:39:19

标签: javascript jquery ajax garbage-collection

情况:

好吧,所以我有一个弹出窗口,该弹出窗口通过ajax从服务器加载一个视图,该视图有时可能具有JavaScript,并且我使用jquery .html(page)

将该视图分配给了该弹出窗口

问题

即使我将新视图加载到弹出窗口中(由于我正在使用html()清除了旧的弹出内容),弹出JavaScript函数和变量仍然有效。

可能的解决方案

如果我在弹出窗口中使用iframe,我认为JavaScript会被清除,因为它会模拟页面刷新,但是还有其他方法吗?我对iframe正确吗?

代码:

没什么特别的,只是一个加载视图的ajax函数:

function ajaxLoad(url1, async, method1, data1, placeOrCallback, loader = false, loadFromParent = false) {
  var placeContent = null;

  $.ajax({
    url: url1,
    headers: {
      'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    },
    async: async,
    cache: false,
    method: method1,
    data: data1,
    beforeSend: function() {
      if (loader) {
        placeContent = $(placeOrCallback).html();
        $(placeOrCallback).html(spinnerLoader);
      }
    },
    error: function(xhr) {
      console.log("An error occured: " + xhr.status + " " + xhr.statusText + " " + url1);
      console.log(xhr.responseJSON);
      for (key in xhr.responseJSON.errors) {
        snackbar(xhr.responseJSON.errors[key]);
      }
      if (loader === true) {
        $(placeOrCallback).html(placeContent);
      }

    },
    success: function(result) {
      if (typeof placeOrCallback === 'function') {
        placeOrCallback(result);
      } else {
        if (loadFromParent === false)
          $(placeOrCallback).html(result);
        else
          $(placeOrCallback, window.parent.document).html(result);
      }
    }
  });
}

以及返回的视图的示例:

<script>
    let variables = "something";
    function finishTrain(e) {
        e.parent().remove();
        let amountDom = $("#armyTrain .card[data-type=infantry] .grid .amount");
        let currentAvailable = amountDom.html();
        amountDom.html(Number(currentAvailable) + 1);

    }

    $("#armyTrain .card:not(.locked) > img").on('click', function (e) {
        let armyInProgress = $("#armyInProgress");
        let type = $(this).parent().attr('data-type');
        let trainTime = $(this).parent().attr('data-trainTime');
        // let trainTime = 5;
        ajaxUpload('{{route('train')}}', true, {'unit': type});
        let card = '<div class="col-1">\n' +
            '            <div class="card">\n' +
            '\n' +
            '                <img src="/images/close.svg" alt="close" class="close-btn w-xm">\n' +
            '                <img src="/images/' + type + '.svg" alt="' + type + '">\n' +
            '\n' +
            '                <div class="in-progress" style="width: 50%;">\n' +
            '\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>';


        armyInProgress.append(card);

        runInProgress(armyInProgress.find(".card").last(), trainTime,0,finishTrain)
    })


    </script>
some html tags ..

0 个答案:

没有答案