Macmod
Macmod

Reputation: 31

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?

Upvotes: 3

Views: 255

Answers (1)

adeneo
adeneo

Reputation: 318322

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)

Upvotes: 1

Related Questions