How come a code like this
var h = $('#searchcontainer').height();
$('#completeholder').css('height', h + 'px');
Works when inside the HTML file itself and not when I load it from a .js file? I tried defining a global var h; inside my main file hoping that the code inside the JS file would work without any luck. Any ideas? Thanks :)
Edit: This one does not work
开发者_运维问答This one works
See the comment at the top of the code :) When you press next on the working page, the css resizes in the end, and that's because I imported the js file into the main header.
I would guess that it has to do with the timing of when it is run. If it is run before the page is loaded, then the objects will not yet be in the page and will not be found.
To make the function work no matter where it is located, put it inside a $(document).ready()
like this:
$(document).ready(function() {
var h = $('#searchcontainer').height();
$('#completeholder').css('height', h + 'px');
});
If what you're really trying to do is share global variables between different $(document).ready(function()
invocations, then you need to declare the global variables outside of $(document).ready(function()
:
var myGlobal;
$(document).ready(function() {
var myGlobal = $('#searchcontainer').height();
});
$(document).ready(function() {
$('#completeholder').css('height', myGlobal + 'px');
});
Globals like this are generally not a good idea in the first place, so what you really ought to do is look for a way to solve this without global variables (like passing parameters to a function call).
Some observations from seeing the actual working and non-working code:
- You have multiple objects with the same id (like
contentholder
). Referencing those objects by id will not work reliably and is prohibited in HTML. - In the inline version, you are setting the height of completeholder in the
case 'NextQuestion1':
block and incase 'NextQuestion2Dance':
, but you are not doing that in the external JS version. That code appears to be what fixes it. On my browser the height gets set to 479 (the correct height) in those case statements. That does not happen in the external JS version so the code is not identical between the two versions.
精彩评论