【问题标题】:wordpress run script once posts have loaded加载帖子后,wordpress运行脚本
【发布时间】:2012-10-30 19:54:22
【问题描述】:

我有一个 wordpress 主题,它有一个动态元素,在加载帖子时由 javascrip(jquery)t 调整大小(单个帖子,而不是列表页面)

所以:

<div class='some-div'>

<div class='content'>
<?php /* code to load posts */ ?>
</div>

目前我使用 javascript 获取 div.content 的高度并将该高度应用于另一个 div.some-div

问题在于连接速度较慢时,高度计算是在内容加载之前完成的

所以,我需要的是仅在帖子完成加载后运行 javascript 函数

目前我在延迟函数,将脚本放在页脚,并使用'defer'属性,但我仍然会发生

有什么想法吗?

【问题讨论】:

  • 当你说你“延迟函数”时,这是否意味着你正在 $(document).ready 上运行代码?
  • Doh,不像傻瓜,我在准备好文档之外运行代码。

标签: javascript jquery wordpress


【解决方案1】:

您为什么不先尝试将该 div 的内容保存到变量中,例如

var my_js_var = <?php echo $content ?> ;

只有当存储到你的 div 的内容等于你的 'my_js_var' 时,才用一个函数来调用 resize div 函数

//Would be something like:
var my_content = <?php echo $content ?> ; //Downloading the content

//Timer to constantly check if the div is loaded correctly
var timer = window.setTimeout('refresh()',100)

function refresh () {
//if the content of your div is equal to 'my_content' variable
//then call the resize function of the div
//finally clear the timeout [clearTimeout(timer)]

}

没有测试过

告诉我它是否有效..

最好的问候

【讨论】:

    【解决方案2】:

    您可以在 onload 事件中运行您的计算,以确保您帖子中的图像、文本等已完成加载。

    <body onload="YourCalculationFunctionHere">
    

    不要使用 jquery 的 .ready() 方法进行计算,因为它会在加载 DOM 之后而不是在加载页面(包括图像、文本等)之后运行。

    http://www.w3schools.com/jsref/event_onload.asp

    【讨论】:

      【解决方案3】:

      只是为了回答以防万一有人遇到同样的问题。

      我在 dom 加载之前运行了这个函数,一个简单的错误很容易解决。

      使用

      $(function(){
        // code here
      });
      

      作为$(document).ready的简写

      【讨论】:

        猜你喜欢
        • 2017-06-14
        • 1970-01-01
        • 2020-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多