SoftTimur SoftTimur - 8 days ago 4
Javascript Question

Simplify a JQuery code

I have many popovers in my page (JSBin), each

data-toggle
is linked to a html div. It is now realized by the following script:

<script>
$('[data-toggle="popover0"]').popover({
html: true,
content: function() {
return $("#popover0-html").html()
}});

$('[data-toggle="popover1"]').popover({
html: true,
content: function() {
return $("#popover1-html").html()
}});

$('[data-toggle="popover2"]').popover({
html: true,
content: function() {
return $("#popover2-html").html()
}});
</script>


I would like to simply the above code by saying "for all data-toggle with an ID, we return the html whose id is
ID
+
-html
". Does anyone know how to realize this?

Answer

One option is:

$('[data-toggle]').popover({
   html: true,
   content: function() {
      var id = "#" + this.getAttribute('data-toggle') + "-html";
      return $(id).html();
   }
});

The above script uses value of the data-toggle attribute for selecting the target element. It works for 1 or many elements.

Comments