Javascript Form How to - Create new button with dynamic function








Question

We would like to know how to create new button with dynamic function.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from w w  w.  j  a  v  a 2s  .com-->
    var x="hi.", b;
    (b = document.createElement("button")).innerHTML = "click me";
    b.setAttribute("onclick", "console.log('"+x+"')");
    document.body.appendChild(b);
}
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: