【问题标题】:Why is this function still running even after the script is removed dynamically?为什么即使在动态删除脚本后该函数仍在运行?
【发布时间】:2017-08-31 22:55:49
【问题描述】:

我正在尝试加载一个新的脚本标记,该标记将 jQuery 内容(在 #clickmeDIV DIV 内)动态替换为新的,但是,一旦将第二个脚本标记加载到 #clickmeDIV DIV 中,第一个脚本即使它不是 DOM 的一部分,replaced 仍在运行。我通过使用 chrome 开发人员工具检查 DOM 确认了这一点。有什么方法可以完全擦除第一个脚本,然后动态替换为新脚本(无需重新加载页面)?

div {
  width: 300px;
  height: 300px;
  background-color: blue;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="clickmeDIV">

  <script>
    $(document).on('click', '#clickmeDIV', function() {

      alert('Alert executed by the original script');
      $('#clickmeDIV').empty();

      $('#clickmeDIV').html('<script type="text/javascript">' +
        '$(document).on("click","#clickmeDIV", function(){' +
        'var foo  = function(){alert("Alert executed by the script inserted dynamically"); }; foo();' +
        '}); </s' + 'cript>');

    });
  </script>

</div>

【问题讨论】:

  • 删除脚本无法撤销已执行代码所做的事情。

标签: javascript jquery html


【解决方案1】:

您将单击事件处理程序附加到 id 为 clickmeDIV 的 div。您可以使用

将其删除
$(document).off('click', '#clickmeDIV');

或者

$('#clickmeDIV').off('click');

阅读更多关于它的信息here

【讨论】:

    【解决方案2】:

    因为它安装了事件处理程序。

    如果要删除处理程序,请使用 jQuery 的 off 函数(相对于 on 函数)。

    根据the jQuery docs

    $( "#clickmeDIV" ).off( "click" );
    

    将删除clickmeDIV div 中的所有点击处理程序。

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 2014-11-03
      • 2022-01-07
      • 1970-01-01
      • 2018-04-27
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多