简体   繁体   中英

Why my Chrome extension event doesn't work?

I'm trying to create a chrome extension. I had a problem with the affectation of event for the new element that i append to the dom of site with content. Js

If I add an event to an element' 'for example class' exist already in the page, it works correctly. Just for my new appended element((in the code iadded a button ,the event is just an alert to test))

function tst() {
  myclass = $("._3hg-._42ft");
  myclass = myclass.not(".supp");
  myclass.addClass("supp");
  var patt = /https:\/\/(.)*\.facebook\.com\/(.)*\/(posts|photos|videos)\/(\w|\.|\d)*/g;
  for (i = 0; i < myclass.length; i++) {
    result = patt.exec(myclass[i]);
    myclass.append('<button class="fact" id=' + result[0] + ' style="position: absolute;">fact</button>');
  };

  /* this is a simple event*/
  /***********************/
  $(".fact").on('click', function() {
    alert("no event work ");
  });

Making somewhat broad assumption here in my answer that it is JavaScript/jQuery related and is NOT an extension...or is so still in that context. You need to attach the event to the container here perhaps for the dynamically created elements. Lots of global stuff, suggested to not do that, updated there.

Appends a lot of buttons perhaps? might need to only hit DOM once but left as-is in this isolated function.

 function tst() { let myclass = $("._3hg-._42ft") .not(".supp"); myclass.addClass("supp"); //let result = {}; var patt = /https:\\/\\/(.)*\\.facebook\\.com\\/(.)*\\/(posts|photos|videos)\\/(\\w|\\.|\\d)*/g; var i = 0; //avoid global for (i; i < myclass.length; i++) { // broad assumption of the returned value from patt.exec() here // not even sure why it needs an id, have a class, use for css let result = patt.exec(myclass[i]); myclass.append('<button class="fact" id="' + result[0] + '">fact</button>'); } /* attache event to pre-existing element */ /***********************/ myclass.on('click', ".fact", function() { alert("event works"); }); }
 button.fact { position: absolute; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM