Javascript inline display difference across browsers?
I have the following inline Javascript code:
<a href="javascript:{ document['example'].src = 'cube.png'; document.getElemen开发者_StackOverflow中文版tById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();'; }">Cube</a>
For your poor tired programmer eyes, here's the expanded version:
document['example'].src = 'cube.png';
document.getElementById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();';
This code acts as a hyperlink that changes the example
image to an image of a 3D cube and changes a <pre id="constructor">
's content to the appropriate constructor. (This is obviously a tutorial page).
This works perfectly fine in Chrome, but in other browsers, I get either a new page or the whole page's content changed to:
Mesh mesh = new Mesh.Cube();
What is the problem with the code? What puzzles me is that it's valid in a browser and not in another. It's as if the script couldn't find the 'constructor' element and proposed the whole page as a fallback. I'm far from being a Javascript expert, so that's just a wild guess.
Well I must say I've never seen this kind of notation in an anchor link, using the braket to put some code in it I mean.
I tried in Chrome, it did work indeed, but not in FireFox.
You may want to try like that though:
href="javascript:(function(){ document['example'].src = 'cube.png'; document.getElementById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();'; })()"
But to be honest I would just create an helper function and call it directly like:
href="javascript:myFunction('Cube')"
Or something like that (even better would be to dynamically attach an event listener to the anchor link)
Try this:
<a href="#" onclick="foo(); return false;">Cube</a>
In your JavaScript code:
function foo () {
document['example'].src = 'cube.png';
document.getElementById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();
}
I will just answer "What is the problem with the code?"
The href
behaves differently than any onXXX event (hence javascript: protocol). It kind of tries to load new document and put something inside. The worst thing, it catches all output. So, to make it work as-is, you need to catch all statement values as assignments:
var x = document['example'].src = 'cube.png';
var y = document.getElementById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();';
all in javascript:{...}
of course.
Also some good comments and explanations here: http://www.west-wind.com/weblog/posts/9899.aspx
精彩评论