Js dynamically adds an onclick event with and without parameters

  • 2020-03-30 03:37:57
  • 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: