Bootstrap popover data from another HTML file

可紊 提交于 2019-12-12 12:29:34

问题


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();
});

回答1:


Lets say you have a template like this :

<h1>header</h1>
<body>this is a test</body>

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'))
    }
});

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 :

demo -> http://plnkr.co/edit/9pHmKBvhxMOdGjCHz2OG?p=preview



来源:https://stackoverflow.com/questions/33146660/bootstrap-popover-data-from-another-html-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!