Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences in browser scope treatment of chrome/firefox

This alerts x in chrome, but not on firefox (Chrome 25.0/FF 11.0):

var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.setAttribute("onclick", "alert(x)"); // Doesn't work on FF, but works on Chrome
document.body.appendChild(b);

It works on both when I use DOM (b.onclick, like the code below), but returns a "x not defined" error when using the attribute in string form, like in the code above.

var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.onclick = function(){alert(x)}; // Works on FF/Chrome
document.body.appendChild(b);

What are the differences between the two browsers that cause this?

like image 746
Macmod Avatar asked Dec 15 '25 15:12

Macmod


1 Answers

This should work in FF and Chrome, but not in IE, you need to actually pass the variable ?

var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.setAttribute("onclick", "alert('"+x+"')");
document.body.appendChild(b);

In (older versions of) IE you can't set inline javascript with setAttribute as far as I know.

FIDDLE (tested in FF 19 and newest Chrome)

like image 73
adeneo Avatar answered Dec 18 '25 09:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!