【问题标题】:js not working in bs3 ajax modaljs在bs3 ajax模式下不起作用
【发布时间】:2013-12-08 05:38:29
【问题描述】:

我的 bs3 模态中的 js 有一些问题 - 它不起作用。我正在使用 ajax 打开模式。

主页

<a href="/modals/comp_activate.php" data-target="#modal-ajax" data-toggle="modal"><i class="fa fa-plus-circle"></i> Activate this computer</a>';

<div class="modal fade" id="modal-ajax" tabindex="-1" role="basic" aria-hidden="true">
    <img src="/assets/img/ajax-modal-loading.gif" alt="" class="loading">
</div>

<script src="/assets/scripts/custom/custom.js" type="text/javascript"></script>
<script>
    jQuery(document).ready(function() {    
        Custom.init();
    });
</script>

custom.js

var Custom = function () {

// private functions & variables

// external window links
var externalWindows = function() {
    $("a[data-window='external']").on('click', function() {
        window.open($(this).attr('href')); 
        return false; 
    });
}

// public functions
return {

    //main function
    init: function () {
        //initialize something here
        externalWindows(); // external window links 
    }

};

}();

模态页面中的链接

<a class="btn btn-primary" href="http://www.somesite.com/" data-window="external" onClick="$('#modal-ajax').modal('hide');"><i class="fa fa-shopping-cart"></i> Purchase Now</a>

所有这一切都是在浏览器的新窗口中打开带有data-window="external" 的任何链接。由于模式页面是使用 ajax 打开的,因此主页中的 js 在加载时不会“拾取”。我也可以在我的模态页面上添加该功能,但它会导致主页出现问题。

我可以在这里做什么?

【问题讨论】:

    标签: javascript jquery ajax twitter-bootstrap


    【解决方案1】:

    您可以使用event delegation 以便动态加载的链接触发您的处理程序:

    var externalWindows = function () {
        function openWindow() {
            window.open($(this).attr('href')); 
            return false;
        }
    
        $("a[data-window='external").click(openWindow);
        $("#modal-ajax").on('click', "a[data-window='external']", openWindow);
    };
    

    【讨论】:

    • 这有效...我在我的 custom.js 文件中添加了另一个函数 `var externalWindows2 = function() { $("#modal-ajax").on('click',"a [data-window='external']", function() { window.open($(this).attr('href')); return false; }); }`这是唯一的方法吗?这意味着我想在远程模态中使用的每个 js 也都需要这个。
    • @user756659 不,不需要第二个功能,只需将您拥有的功能更改为我发布的功能即可,一切正常
    • 嗯,我需要它在所有页面上工作......不仅仅是模态,而是'with' ajax modals。
    • 切换 #modal-ajax for body 似乎可以解决问题,尽管我认为 body 会与我原来的效果相同?不过,它适用于常规页面和模式。
    • @user756659 是的,通常使用document 而不是body 但这样做是将处理程序附加到页面上的每次点击,这最终可能会影响您网站的性能,由于事件传播,它与您的原始代码不一样,请查看我给您的链接以供参考,还请查看 jquery 的on() 的参考
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 2016-09-28
    • 2019-12-03
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多