图像仅在调试时显示(image shows only when debugging)

编程入门 行业动态 更新时间:2024-10-27 01:28:38
图像仅在调试时显示(image shows only when debugging)

我有一个包含像这样的img的局部视图:

<img src="" alt="test" id="chartImage" style="display: none;" />

然后在我看来,包含它我的JavaScript看起来像这样:

if ($(this).val() != '') { setTimeout(function() { $('#chartImage').attr("style", "") }, 1); }

如果我不放超时图像不显示。 但是,如果我不设置超时时间,并且在设置attr之前发出警报,则会显示图像。 有点奇怪?

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 timeout and I put an alert prior to setting the attr the image appears. Kinda weird?

最满意答案

如果要在页面加载时遍历DOM,则必须等待页面完成加载并构建整个DOM树。 否则,当浏览器读入特定的代码行(通常在HTML <head> )时,会立即解释Javascript,而所需的DOM元素(稍后在<body> )尚未完全构建。

您通常将一个函数挂接到window.onload事件,但在jQuery中,您可以将ready事件挂接到document以在文档完成加载/构建时执行某些操作。

<head> <script type="text/javascript"> $(document).ready(init); function init() { // Now you can access any DOM element here. } </script> </head>

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>

更多推荐

本文发布于:2023-08-04 15:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417836.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   image   debugging   shows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!