Javascript function call from html file

I have this JavaScript code:

var cr = {};
cr.plugins_ = {};
cr.runtime = null;

cr.plugins_.Vinoos_Markets = function(runtime) {
    this.runtime = runtime;
};
(function() {
	function initialize_events(result) {
		alert(result);
	}
})();
<button onclick="initialize_events('Test Result');">Send Result</button>
Run code

how to run initialize_events function from html by clicking a button?

I do not have permission to edit the JavaScript file.

+4
source share
1 answer

I do not have access to edit the js file.

Then you cannot stop completely. It is completely closed to the anonymous IIFE * that covers it. You must expose it as global in order to use it with the onxyz-attribute-style event handler (and this will require changing the JavaScript code). This is one of many reasons not to use them.

JavaScript, , , , / JavaScript:

IIFE data-*, , :

var cr = {};
cr.plugins_ = {};
cr.runtime = null;

cr.plugins_.Vinoos_Markets = function(runtime) {
  this.runtime = runtime;
};
(function() {
  function initialize_events(result) {
    alert(result);
  }
  document.getElementById("send-result").addEventListener("click", function() {
    initialize_events(this.getAttribute("data-result"));
  }, false);
}());
<button id="send-result" data-result="Test Result">Send Result</button>

:

  • addEventListener (, IE8, , , ), . - .
  • IIFE, , , data-*.
  • ID getElementById - ; , , , . CSS- document.querySelector.

* IIFE = , , (function() { /*...*/})(); ( " inline-called". " ", : , , .)

+13

Source: https://habr.com/ru/post/1682301/


All Articles