Bootstrap 引导弹出窗口不是函数

798qvoo8  于 2022-12-07  发布在  Bootstrap
关注(0)|答案(1)|浏览(185)

I am currently trying to develop a Chrome plugin that spots occurrences of different names inside each visited web page.
When the plugin finds a name, it basically adds an icon next to it. When clicked, a bootstrap popover should appear with more information about the person.
When I try to run my code, I get this error:
VM887:1 Uncaught TypeError: $(...).popover is not a function(…)
Here is my code:

$('head').append('<script async src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>\
<script async src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>');

$(document).ready(function(){
  var name = "Nicolas";
  // console.log('Document is ready.. scanning for politicians...');
  //var hashmap = db_reader.getHashMap();

  var counter = {i: 0}; //Occurences. Singleton to be passed by reference and not by value.
  $('p').each(function(index) {
    addImage(this, counter);
  });

  $('li').each(function(index) {
    addImage(this, counter)
  });

  $('head').append(
    "<script>$(function(){$('[data-toggle=\"popover\"]').popover();});\
</script>"
  );

});

function addImage(context, counter) {
  var body = $(context).text();
  var word;
  var reg = /[A-Z]+[a-z]*/gm;
  while(word = reg.exec(body)){
    // console.log("while");
    if(word == name){
      // console.log(word);
      var image = '<a href="#" data-toggle="popover" title="Popover Header" data-content="A wonderful content" id="popover'+counter.i+'" class="politicianFind">\
<img alt="name" src="https://s15.postimg.org/pei4ci3fv/fdp.png">\
</a>';
      // console.log("Replacing HTML");
      $(context).html(body.replace(word, word + " " + image));
      counter.i++;
    }
  }
}

I have already searched a lot but I wasn't able to find any fix for this issue.
Kind regards,
Florian

unguejic

unguejic1#

I think that it's because when you call the method popover the bootstrap script not yet loaded.
You have 2 options:

  1. To call the method on $(window).load - http://output.jsbin.com/qoteqe
  2. Include the bootstrap and jQuery references in the DOM and not load them in the script: http://output.jsbin.com/tamoda

By the way why do you add another jQuery reference? If you are using $('head').append clearly you have jQuery in your page already. Isn't?

相关问题