从另一个HTML文件引导弹出窗口数据 [英] Bootstrap popover data from another HTML file
问题描述
我希望它从html文件(如果需要的话)中检索数据,而不是对数据进行硬编码.我怎样才能做到这一点?假设我还有一个带有<h1>
和<body>
的html文件,并且弹出框应该从中获取数据(弹出框的标题/正文)
Instead of the data being hardcoded, I want it to retrieve it from a html file, a template if you will. How can I do this? Let's say I have another html file with a <h1>
and a <body>
, and the popover should get the data from it (header/body of the popover)
<button type="button" class="btn btn-default" title="Help" data-toggle="popover" data-content="423241421453453"><span class="glyphicon glyphicon-info-sign" style="font-size: 20px; padding-top:5px"></span></button>
</div>
$(document).ready(function popover() {
$('[data-toggle="popover"]').popover();
});
推荐答案
假设您有一个这样的模板:
Lets say you have a template like this :
<h1>header</h1>
<body>this is a test</body>
然后将模板文件名作为data-templatefile
属性添加到您的按钮标记中:
Then add the template filename as a data-templatefile
attribute to your button markup :
<button type="button" data-templatefile="template.html" class="btn btn-default" title="Help" data-toggle="popover"><span class="glyphicon glyphicon-info-sign" style="font-size: 20px; padding-top:5px"></span></button>
然后像这样初始化弹出窗口:
Then initialise the popover like this :
$('[data-toggle="popover"]').popover({
html : true,
content : function() {
return loadContent($(this).data('templatefile'))
}
});
这是前进的方向. loadContent()
需要更加棘手.如果使用jQuery解析内容,则会看到<body>
标记被剥离.这是这样做的浏览器,而不是jQuery.但是,您可以使用DOMParser
来确切地提取要在弹出窗口中使用的那些标签:
This was straigt forward. The loadContent()
needs to be more tricky. If you use jQuery to parse the content you will see that the <body>
tag is stripped out. This is the browser doing that, not jQuery. But you can use a DOMParser
instead to extract exactly those tags you want to use in the popover :
function loadContent(templateFile) {
return $('<div>').load(templateFile, function(html) {
parser = new DOMParser();
doc = parser.parseFromString(html, "text/html");
return doc.querySelector('h1').outerHTML + doc.querySelector('body').outerHTML;
})
}
结果将如下所示:
The result will look like this :
演示-> http://plnkr.co/edit/9pHmKBvhxMOdGjCHz2OG?p =预览
demo -> http://plnkr.co/edit/9pHmKBvhxMOdGjCHz2OG?p=preview
这篇关于从另一个HTML文件引导弹出窗口数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!