代码之家  ›  专栏  ›  技术社区  ›  Ajax1234

使用Jquery动态删除脚本标记时出现问题

  •  1
  • Ajax1234  · 技术社区  · 6 年前

    $(document).ready 函数,该函数使用javascript从包含按钮的html文件中检测按钮单击。我的主html文件的脚本标记指向头中的每个文件:

    file1.js :

    $(document).ready(function(){
      $('.wrapper').on('click', '.click_1', function(){
        alert('hello from the first file');
      });
    });
    

    file2.js :

    $(document).ready(function(){
      $('.wrapper').on('click', '.click_2', function(){
       alert('hello from the second file');
      });
    });
    

    但是,我的目标是能够动态地从头文件中删除其中一个脚本标记(第二个文件中的javascript)及其功能。为此,我在主html文件中创建了一个脚本,通过 src 属性。然而,尽管对页面源代码的检查显示第三个脚本标记确实已被删除,但其功能仍然存在。例如,即使单击 .remove_2 按钮,我仍然可以点击 .click_2 按钮并接收 "hello from the second file" 警觉的:

    main.html :

    <html>
     <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script type="text/javascript" src="file1.js"></script>
        <script type="text/javascript" src="file2.js"></script>
      </head>
       <body>
         <div class="wrapper">
             <button class='click_1'>File1</button>
             <button class='click_2'>File2</button>
             <button class='remove_2'>Remove File2</button>
         </div>
       </body>
       <script>
        $(document).ready(function(){
         $('.wrapper').on('click', '.remove_2', function(){
           $('script[src="file2.js"]').remove();
         });
       });
       </script>
     </html>
    

    简而言之,我希望能够动态删除一个脚本标记,这样标记所指向的文件中的javascript就不再对html页面有任何影响。然而,我没能做到这一点。有人能告诉我我的代码有什么问题吗?还有,我想实现的目标是可能的吗?非常感谢。

    2 回复  |  直到 6 年前
        1
  •  2
  •   gaetanoM    6 年前

    删除外部脚本不会删除事件处理程序。它们附加到当前文档中。

    解决方案可以是:

    1. 删除脚本
    2. 获取所有html页
    3. 用新内容替换html页

      $('.wrapper').on('click', '.remove_2', function(){
          $('script[src="file2.js"]').remove();
          var html = document.documentElement.innerHTML;
          document.open('text/html');
          document.write(html);
          document.close();
      });
      

    在jQuery中,删除脚本后仅替换头:

    $('.wrapper').on('click', '.remove_2', function(){
        var header = $('html head');
        header.find('script[src="file2.js"]').remove();
        $('html head').replaceWith(header);
    });
    
        2
  •  1
  •   Morris    6 年前

    unbinding

    $('.click_2').unbind("click");
    

    $('.click_2').off( "click", "**" );
    

    http://api.jquery.com/off/

    也就是说,您似乎使用了一种相当奇特的方法来禁用单击功能。