image shows only when debugging
I have a partial view that contains an img like so:
<img src="" alt="test" id="chartImage" style="display: none;" />
And then in my view that contains it my javascript looks like this:
if ($(this).val() != '') {
setTimeout(function() {
$('#chartImage').attr("style", "")
}, 1);
}
If I don't put the timeout the image does not show. However, if I don't put the t开发者_如何学Goimeout and I put an alert prior to setting the attr the image appears. Kinda weird?
If you want to traverse the DOM while the page loads, you have to wait for the page to finish loading and building up the whole DOM tree. Otherwise the Javascript is interpreted immediately as the browser reads in the particular code line (usually in the HTML <head>
) while the desired DOM element (which appears later in <body>
) insn't built up fully yet.
You normally hook a function to the window.onload
event, but in in jQuery you can hook up the ready
event to the document
to execute something when the document is finished loading/building.
<head>
<script type="text/javascript">
$(document).ready(init);
function init() {
// Now you can access any DOM element here.
}
</script>
</head>
When are you running you script? You should run it when the DOM is ready for manipulation. Try:
$(function () {
// do your stuff here
});
Shouldn't you be doing $('#chartImage').css('display', '');
精彩评论