add onclick new Function
/Html JavaSript/add onclick new Function.html
<button id="b1">b1</button><button id="b2">b2</button>
<button id="b3">b3</button><button id="b4">b4</button>
<script type="text/javascript">
// Gestion pas ok (b.id est évalué lorsque l'event est levé => b=="foo") :
b = document.getElementById("b1");
b.onclick = function(e) {alert("je suis " + b.id);}; // not ok (b=="foo")
// Gestion par création litérale d'une fonction :
b = document.getElementById("b2");
b.onclick = new Function("alert('je suis "+ b.id +"');"); // ok
// Gestion par "Event" :
b = document.getElementById("b3");
b.onclick = function(e) {
if(!e)e = window.event; // not standard for IE
var target = e.target;
if(!target)target = e.srcElement; // not standard for IE
alert("je suis " + target.id);
}; // ok
// Gestion pat "this" : (----- CONSEILLÉ -----)
b = document.getElementById("b4");
b.onclick = function(e) {alert("je suis " + this.id);};
//ou
function myOnclick(e) {alert("je suis " + this.id);}
b.onclick = myOnclick;
b = "foo";
</script>