Two ways in which js assigns a value to onclick to pass a parameter

  • 2020-03-30 00:00:39
  • OfStack

1) when a method has no arguments, the assignment can be done directly with the onclick = method name

  window.onload = function() {
        $('btnTest').onclick = test;   
  }
  function test() {
        alert(val);
  }

2) when the method has parameters, the error occurs when using onclick = method name (parameter), so we need to add function() before the method name.

  window.onload = function() {
        $('btnTest').onclick = function() { test(1) };   
  }
  function test(val) {
        alert(val);
  }

Related articles: