简体   繁体   English

显示Bootstrap模态时链接的JavaScript不起作用

[英]Linked JavaScript not working when Bootstrap modal is shown

After Bootstrap modal is shown, my app JavaScript is not working. 显示Bootstrap模态后,我的应用JavaScript无法正常工作。

When I execute JavaScript from console then it is working, but my app JavaScript does not work. 当我从控制台执行JavaScript时,它可以工作,但是我的应用程序JavaScript不起作用。

Can somebody please give me advice how I can solve this issue? 有人可以给我建议如何解决这个问题吗?

HTML file: HTML档案:

<button type="button" class="btn btn-primary" id="save-category">Save changes</button>

JavaScript file: JavaScript文件:

var jquery = jQuery.noConflict();

jquery(window).load(function() {

jquery('#add-category').click(function() {
    jquery.get('api/categories/add', function(data) {
        jquery('#modal-target').replaceWith(data);
        jquery('#myModal').modal('show');
    });
});

jquery('#save-category').click(function() {
    jquery('#myModal').modal('hide');
});

});

What is happening here is that the #save-category button is not registered to the event that you made when the page first loads. 这里发生的是, #save-category按钮未注册到页面首次加载时所发生的事件。 This is because bootstrap moves the original DOM element to the modal window, thus losing the original click event. 这是因为引导程序将原始DOM元素移到了模式窗口,从而丢失了原始click事件。

To fix this, you should register your click event to after you show your modal view: 要解决此问题,请在显示模式视图后将click事件注册到:

jquery('#add-category').click(function() {
    jquery.get('api/categories/add', function(data) {
        jquery('#modal-target').replaceWith(data);
        jquery('#myModal').modal('show');

        // Register the event here
        jquery('#save-category').click(function() {
            jquery('#myModal').modal('hide');
        });
    });
});

Also note that the load event has been deprecated in jQuery 1.8 so you might want to use jQuery(document).ready( for initialising your script code unless you need to wait for images to load. 还要注意,在jQuery 1.8中不推荐使用load事件,因此除非您需要等待图像加载,否则您可能要使用jQuery(document).ready(来初始化脚本代码)。

What is happening here is that the #save-category button is not registered to the event that you made when the page first loads. 这里发生的是,#save-category按钮未注册到页面首次加载时所发生的事件。 This is because bootstrap moves the original DOM element to the modal window, thus losing the original click event. 这是因为引导程序将原始DOM元素移到了模式窗口,从而丢失了原始click事件。

Try to use delegate instead of event binding 尝试使用委托代替事件绑定

jquery('#add-category').click(function() {
    jquery.get('api/categories/add', function(data) {
        jquery('#modal-target').replaceWith(data);
        jquery('#myModal').modal('show');
    });
});

jquery(document).on('click', '#save-category', function() {
    jquery('#myModal').modal('hide');
});

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

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