我遇到了一个问题,一张表中有超过 10 个弹出窗口。它们都应该在悬停时显示弹出窗口,并且具有相似的 html,但内容有所不同。我将其设为最简单的方法,但我觉得一定有更聪明的方法来做到这一点。
是否可以让这个 js 代码更 DRY?
$('#static-pop-1').popover({
'trigger': 'hover',
'placement': 'bottom',
'html': true,
'content': '<div class="static-popover"><span>Hey!</span></div>'
});
$('#static-pop-2').popover({
'trigger': 'hover',
'placement': 'bottom',
'html': true,
'content': '<div class="static-popover"><span>Hey 2!</span></div>'
});
最佳答案
假设您不希望弹出窗口只说Hey 1
、Hey 2
等,但实际上在每个内容中设置了不同的内容,但保留其余内容设置相同,你可以做
var settings = {
trigger : 'hover',
placement : 'bottom',
html : true
}
$('#static-pop-1').popover($.extend({}, settings, {
content: '<div class="static-popover"><span>Hey!</span></div>'
}));
$('#static-pop-2').popover($.extend({}, settings, {
content: '<div class="static-popover"><span>Hey 2!</span></div>'
}));
$('#static-pop-3').popover($.extend({}, settings, {
content: '<div class="static-popover"><span>Hey 3!</span></div>'
}));
或者你可以使用一个函数
function setting(text) {
return {
trigger : 'hover',
placement : 'bottom',
html : true,
content : '<div class="static-popover"><span>'+text+'</span></div>'
}
}
$('#static-pop-1').popover(setting('Hey!'));
$('#static-pop-2').popover(setting('Hey 2!'));
$('#static-pop-3').popover(setting('Hey 3!'));
关于javascript - 是否可以使多个 Bootstrap 弹出窗口更干?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28136787/