添加alert()会使“脚本不工作”正常工作
我必须重写几年前编写的代码才能与现代浏览器一起使用。该站点包含几个 Javascript 文件。
其中有一段类似这样的代码 - 它动态生成 DOM 元素:
createTabs();
createTabsContent();
现在,我在 Chrome 中打开网站,加载页面后我尝试更改一些新生成的元素样式,
document.getElementById('element').style.display = 'none';
但它不起作用 - 要么是表单脚本或 Chrome 控制台。是的,具有 id #element 的元素存在于 DOM 中)。奇怪的是——Chrome 不报告任何错误。
但是,当我修改代码并执行类似操作时:
alert('test'); //i put alert here
createTabs();
createTabsContent();
//alert('test'); // or put it here
一切正常。
在其他浏览器中:IE8、FF、Opera 一切正常,也没有错误。 我使用了 jQuery document.ready,然后尝试了 window.onload 事件 - 但他们失败了 - 没有任何改变。
什么可能导致此行为?
I have a to rewrite code written couple of years ago to work with modern browsers. That site includes couple of Javascript files.
In on of them there is a code something like this - it's generating DOM elements dynamically:
createTabs();
createTabsContent();
Now, I'm opening site in Chrome and after page is loaded I try to change some fresh generated element style by
document.getElementById('element').style.display = 'none';
and it's not working - either form script or Chrome console. Yes, element with id #element exists in DOM). What is wierd - Chrome doesn't reporting any errors.
But, when I modify code and do something like that:
alert('test'); //i put alert here
createTabs();
createTabsContent();
//alert('test'); // or put it here
everything working properly.
In other browsers: IE8, FF, Opera everything works, also no errors.
I used jQuery document.ready, then tried with window.onload events - and they failed - nothing changed.
What may cause this behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这种与 DOM 相关的东西不起作用,但在添加警报时开始起作用的症状通常可以通过推迟第二步来解决:
IE 特别容易出现无法立即准备好进行交互的情况。我在 Chrome 上还没有遇到过太多这样的情况。
This symptom of something DOM-related not working, but starting to work when an alert is added is usually solvable by deferring the second step:
IE is especially prone to things not instantly being ready to be interacted with. I haven't really encountered it much with Chrome.
当代码在插入警报后“工作”时,通常意味着您通过暂停执行警报来绕过某种竞争条件。例如,您可能有一个 AJAX 请求,后跟一个函数调用,该函数调用应该对 AJAX 结果起作用(但是在 AJAX 请求之后调用不正确,而不是在完成时传递给 AJAX 处理程序调用)。如果没有警报,该函数还没有数据,因此会失败,但是当您放入警报时,请求有完成所需的时间,并且函数会成功。
如果没有更多有关代码的上下文,很难确定您遇到的问题是由于什么原因造成的。
When code "works" after you insert an alert, it usually means that there is some sort of race condition that you are bypassing by having the alert pause execution. For instance, you might have an AJAX request followed by a function call which is supposed to work on the AJAX result (however is called improperly after the AJAX request instead of being passed in to be called by the AJAX handler on completion). Without an alert, the function doesn't have the data yet, so it fails, but when you put an alert in, the request has the time needed to complete and the function succeeds.
It is hard to say for sure what the problem you are experiencing is due to without having more context about your code.