在模态中加载iframe,替换.modal-content

时间:2015-06-03 09:39:24

标签: javascript jquery twitter-bootstrap iframe

我有以下HTML:

<a href="http://domainx.com/" class="btn btn-primary" data-toggle="modal" data-target="#myModal">LINKY</a>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                <iframe src="http://domainy.com/" width="100%" height="380" frameborder="0"
                        allowtransparency="true"></iframe>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

当我使用以下JS更改模态iframe src时,.modal-content的内容将被切换模式的按钮上的HREF加载的HTML完全覆盖。

$('[data-target="#myModal"]').on('click', function (e) {
    e.preventDefault();

    var _linky = $(this).attr('href');
    var _target = $(this).data('target');

    if (_target.length > 0) {
        _target.find('iframe').attr('src', 'about:blank');

        var _isRemote = false;
        if (_linky.indexOf('http') > -1) {
            _isRemote = true;
        }

        if (!_isRemote) {
            if (_linky.indexOf('?') > -1) {
                _linky += '&tmpl=component';
            } else {
                _linky += '?tmpl=component';
            }
        }

        _target.find('iframe').attr('src', _linky).load(function() {
            _target.modal('show');
        });
    }
});

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});

如何阻止Bootstrap替换.modal-content中的所有内容?

1 个答案:

答案 0 :(得分:0)

_target是一个简单的字符串值,表示元素ID - 而不是jQuery对象。

代码已修复并更新:http://codepen.io/TheFoot/pen/QbpMYx