我有 jQuery v1.8.3 和 twitter-bootstrap v2.2.1
我想创建一个函数来动态显示消息。
function showMsg(header, text, closeFunc) {
var randId = Math.round(Math.random()*1000000);
var dialog = '<div id="modal_' + randId + '" class="modal hide fade">';
dialog += '<div class="modal-header">';
dialog += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>';
dialog += '<h3>' + header + '</h3>';
dialog += '</div>';
dialog += '<div class="modal-body">';
dialog += text;
dialog += '</div>';
dialog += '<div class="modal-footer">';
dialog += '<button id="modalBtn_' + randId + '" class="btn btn-primary">Close</button>';
dialog += '</div>';
dialog += '</div>';
$('body').append(dialog);
var modal = $('#modal_' + randId);
modal.modal({backdrop : false, show : false, keyboard : false});
modal.modal('show');
var btn = $('#modalBtn_' + randId);
btn.click(function(){
closeFunc();
modal.modal('hide');
});
}
但是在一次显示 3 条以上这些消息后,我在 Jquery 中收到错误:太多递归
我该如何修复它或有其他方法?
最佳答案
我无法重新创建您的“太多递归”错误,但我确实想建议一种比您当前拥有的代码更好的处理动态消息的方法。也就是说,您可以只使用单个模态并在显示之前更新其中的内容。这将消除您目前产生的所有开销
- 让 jQuery 重复将相同的字符串解析为 html;
- 为每条消息实例化一个新的 Modal 对象;和
- 生成随机 ID,然后在 DOM 中搜索用它们创建的元素。
作为替代方案,从一开始就在标记中包含以下空白模态。位置并不重要,重要的是 <body>
的底部是一个典型的位置。如果您必须动态生成它,请在showMsg
之外进行。函数并且只执行一次。
<div id="msgModal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3></h3>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button class="btn btn-primary callback-btn" data-dismiss="modal">Close</button>
</div>
</div>
请注意,我确实对您的进行了一些更改,添加了固定的 id="msgModal"
到模态并添加类 callback-btn
和属性 data-dismiss="modal"
到button
.
然后是showMsg
的代码可能是:
var $msgModal = $('#msgModal').modal({
backdrop: false,
show: false,
keyboard: false
}),
showMsg = function (header, body, callback) {
$msgModal
.find('.modal-header > h3').text(header).end()
.find('.modal-body').text(body).end()
.find('.callback-btn').off('click.callback')
.on('click.callback', callback).end()
.modal('show');
};
这是一个演示,如果单击页脚按钮,则会输出到控制台:
Plnkr
关于javascript - twitter bootstrap 动态显示模态 - 递归错误太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594495/