繁体   English   中英

将Javascript依赖项添加到使用Jquery加载到Ajax中的HTML文件中

[英]Add a Javascript dependency to an HTML file loaded in Ajax with Jquery

这是我正在尝试做的事情(请在帖子的最后检查以查看我的问题):

我有2个html文件:index.html和modal.html。 还有2个JavaScript文件:script.js和modal.js

我希望通过Ajax调用将modal.html加载到index.html中,并且仅在加载modal.html时才加载modal.js。

这实际上有效,但是是否有可能使modal.js仅适用于modal.html(使其充当特定的控制器)? 还是有可能卸载modal.js?

我的代码如下,您可以了解我的问题:

Index.html

<a href="modal.html" class="open-modal">Open a modal</a>

<a href="" class="specific-action">Both on index.html and modal.html</a>

<script src="js/script.js"></script>

modal.html

<div class="modal-content">
    <h2>My Modal</h2>
    <a href="" class="specific-action">Both on index.html and modal.html</a>
    <a href="" class="close-modal">close the modal</a>
</div>

script.js

$(".open-modal").click(function(e){
    e.preventDefault();
    var modalURL = $(this).attr("href");
    $("body").prepend($("<div/>").attr("id", "modal-container-global"));
    $("#modal-container-global").load(modalURL, function(response, status, xhr){
        if(status == "success"){
            $.getScript( "js/modal.js" );
        }
    });
})

modal.js

$(".specific-action").click(function(e){
    e.preventDefault();
    console.log("testing");
})

$(".close-modal").click(function(e){
    e.preventDefault();
    $("#modal-container-global").remove();
})

这段代码有效,但是我有3个问题:

  1. 按钮.specific-action既适用于索引又适用于模态=>是否可以使其仅适用于模态?
  2. 在script.js上,每次加载modal.html时都会加载modal.js。 如果我不这样做,由于DOM在加载后=>用于大型脚本后发生了变化,因此modal.js将不适用于modal.html,这会影响性能吗?
  3. 删除模态时,modal.js仍处于活动状态。 有没有办法删除此文件或使其不活动?

当您将事件绑定到带有特殊类的元素时,事件将一直保留到元素存在为止。 区分元素的一种简单方法是在模态DOM电子结构中添加一个标识:

<div id="my-modal" class="modal-content">

并使用此ID将与模式有关的所有事件绑定:

// On modal.js
$("#my-modal .specific-action").click(...)

然后,当您卸载或删除模态的元素时,它们的事件也将被删除。

  1. 使选择器更具体,因此您仅将目标定位在模态$(".modal-content .specific-action")
  2. 如果将相同的事件处理程序重复添加到现有元素或覆盖现有的变量/对象等,则多次加载相同的脚本可能会很棘手。基于您正在使用的代码,没有简单的答案
  3. 您无法删除已编译的脚本

无需多次加载modal.js 将一个变量添加到modal.js并检查其是否存在。 这样的事情。

//modal.js
var modal_loaded = 123;
function initModal(){
$("#modal-container-global .specific-action")//restrict .specific-action to modal
  .click(function(e){
    e.preventDefault();
    console.log("testing");
})

$(".close-modal").click(function(e){
    e.preventDefault();
    $("#modal-container-global").remove();
})
}//initModal

//script.js
$(".open-modal").click(function(e){
    e.preventDefault();
    var modalURL = $(this).attr("href");
    $("body").prepend($("<div/>").attr("id", "modal-container-global"));
    $("#modal-container-global").load(modalURL, function(response, status, xhr){
        if(status == "success"){
            if(modal_loaded !== undefined)
                initModal();
            else
                $.getScript( "js/modal.js", initModal);
        }
    });
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM