简体   繁体   中英

Is there a way to make a function that can be accessed later in a google chrome extension?

I am trying to make an extension that makes a button which then executes a function, however, because the extension executes a javascript file after the page loads. However, when I create the button I want to run a function. Is there a way I can store a function and variables that can be run and access later by the button?

var effect = [[1,100],[2,32], [5,3]];
var points = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][0];};return adding;})()
var score = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][1];};return adding;})()
var percentage=(score/points*100).toString()+"%";
this.effect = effect;
this.points = points;
this.score = score;
var percentage = points/score;
function list_effect(){
    var effect_string = "";
    for(var i = 0; i<effect.length;i++){
        effect_string += ((points-effect[i][0])/score) - ((points)/score);
    }
    alert(effect_string);
}
if(percentage == 'NaN%'){
//  alert('ERROR');
}else{
  document.getElementsByClassName("agenda")[0].innerHTML = "<button type=\'button\' id=\'get_list\'>Get List</button>"+ document.getElementsByClassName("agenda")[0].innerHTML;
  document.getElementsByClassName("agenda")[0].innerHTML += "<script>" + "this.effect=" + effect.toString() + ";\nthis.points=" + points.toString()+ ";\nthis.score=" + score.toString() +"document.getElementById(\"get_list\").addEventListener(\"onclick\", list_effect());" + "</script>"
}

I have tryied useing this. however that does not work

  1. <script> won't run when added via innerHTML, you should add it using appendChild
  2. normally you don't need to add a <script> element at all, just use createElement and attach the listeners directly
var button = document.createElement('button');
button.id = 'get_list';
button.onclick = function (e) {
  // use your variables here directly  
};
// clear the previous contents
document.querySelector('.agenda').textContent = '';
// add the button
document.querySelector('.agenda').appendChild(button);

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