模态窗口不会出现

时间:2014-05-13 11:51:51

标签: javascript php jquery modal-dialog

我有一个jQuery代码 - 想要在地址适合ID后显示一个模态窗口:

<script type="text/javascript"> 
    $(document).ready(function(){
        var split = location.search.replace('?', '').split('=');
        var i = split[1];

        if(i){

            $('#myModal').modal('show'); 
        }
        else
        {
            document.location.href="/";
        }
    });
</script>

HTML代码:下面是一个想要查看的元素,位于文件index.php

    <div class="modal fade" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                <h4 class="modal-title">Title</h4>
            </div>

            <div class="modal-body">
                <h3>Overflowing text to show scroll behavior</h3>

                <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.<br />

                Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.<br />

                Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
            </div>

            <div class="modal-footer">
                <a href="#" id="clk" class="btn" data-dismiss="modal">Cancel</a>
                <a href="#" class="btn btn-primary">OK</a>
            </div>
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

不要使用split()方法,而是使用match()

$(document).ready(function() {
    var arr = location.search.match(/[?&]id=(\d+)/i);
    if (arr && arr[1] > 0) {
        $('#myModal').modal('show');
    }
    else
    {
        location.href="/";
    }
});

答案 1 :(得分:0)

从您在代码中使用的类中,我假设您使用Bootstrap(很可能是Bootstrap3)。在这种情况下,您可能想尝试这个:

JS:

<script type="text/javascript"> 
    $(document).ready(function(){
        var someVar = location.search.replace('?', '').split('='); //modified
        var i = someVar[1]; //modified
        //don't use "split" as variable name because this is a jquery function and might cause problems

        if(i){

            $('#myModal').modal({show: true}); //modified
        }
        else
        {
            document.location.href="/";
        }
    });
</script>