jquery Ready 函数未执行

发布于 2024-10-02 07:39:15 字数 610 浏览 6 评论 0原文

我在 jquery $(document).ready 函数中放置了一些 javascript。它在 url 中搜索锚点,然后运行一个单独的函数来显示匹配的内容。

如果我在 if 语句中的某处放置警报,则代码将执行,但否则不会运行。我已将所有锚点名称存储在名为“anchorNameList”的数组中,并检查 URL 中的锚点是否存在。

我只希望该函数在初始页面加载时运行,因此我将“currentAnchor”的默认值设置为 1000,并在每次迭代时更改它。

        if (currentAnchor == 1000 && document.location.hash.substring(1)) {
        var checkForThisAnchor = document.location.hash.substring(1);
        for (var j=0; j < anchorNameList.length; j++) {
            if (anchorNameList[j] == checkForThisAnchor) {
                expandMe(j);
            }
        }
    }

I have some javascript placed inside of the jquery $(document).ready function. It searches for an anchor in the url, and then runs a separate function to display matching content.

The code executes if I place an alert inside of the if statement somewhere, but wont' run otherwise. I've stored all the anchor names in an array called 'anchorNameList', and am checking to see if the anchor in the URL exists.

I only want the function to run on the initial pageload, so I set the default value of 'currentAnchor' to 1000 and change it on each iteration.

        if (currentAnchor == 1000 && document.location.hash.substring(1)) {
        var checkForThisAnchor = document.location.hash.substring(1);
        for (var j=0; j < anchorNameList.length; j++) {
            if (anchorNameList[j] == checkForThisAnchor) {
                expandMe(j);
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱娆 2024-10-09 07:39:15

根据我的经验,当 JavaScript 问题通过在某处添加无害的alert() 神奇地自行修复时,问题的根源通常是异步请求。

在非警报情况下,异步请求尚未完成。但是通过添加警报,它有机会完成,因此允许您的代码运行与没有完整异步调用响应的情况下不同的代码路径。

In my experience, when a JavaScript problem magically fixes itself by adding an innocuous alert() somewhere, the source of the problem is typically an asynchronous request.

Under non-alert circumstances the async request hasn't finished yet. But by adding the alert, it has a chance to finish, and therefore allowing your code to travel a different code-path than it would have hit without the response of the complete asynchronous call.

樱&纷飞 2024-10-09 07:39:15

我将onload事件从jQuery的document.ready切换到window.ready。大约 30% 的时间它工作正常,所以这绝对是一个时间问题。页面上检索列表项的主要 JavaScript 函数似乎运行缓慢。我只是将整个扩展函数移至列表检索函数的末尾,因此它只是线性运行。

I switched the onload event from jQuery's document.ready to window.ready. It worked properly about 30% of the time, so it was definitely a timing issue. It seemed the main JavaScript function on the page, which is retrieving list items, was running slowly. I just moved this entire expanding function to the end of that list retrieval function, so it just runs linearly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文