You may have known quite a few methods to bind a handler to the click event on an element, two of which are using the onclick attribute and the onclick property, like:
<li id="li" onclick="alert('hello');">content</li>
<li id="li">content</li> <script> var li=document.getElementById("li"); li.onclick =function(e){ alert("hello"); } </script>
What is the difference between the onclick attribute and the onclick property? Well, in modern browsers, the onclick attribute is a string which represents a piece of valid javascript code, while the onclick property is a function(reference). The onclick attribute will be used to generate the onclick property which is an anonymous function containing the js code. If you use both the onclick attribute and the onclick property, the code of the onclick attribute will be overwritten and you have got only one event handler.
Note that the following usage of the onclick attribute is not correct.
<li id="li" onclick="function(e){alert('hello');}">content</li>
and will produce the error “Uncaught SyntaxError: function statement requires a name”. This is because an anonymous function cannot be defined without using it. Giving a name to the function does not work as you expect:
<li id="li" onclick="function a(e){alert('hello');}">content</li>
This time, no error is produced but you cannot see the alert window because the code just contains the declaration of the function, not the execution of the function. The correct usage is:
<li id="li" onclick="function a(e){alert('hello');a();} ">content</li>
You can see the code in the onclick attribute becomes complex and not easy to read. If you need complex handler logic, you’d better use the onclick property. In fact, I do not suggest to use the onclick attribute except for very simple cases as the hidden logic under the hood of the onclick attribute may surprise you.