-1

我想使用 jQuery 添加计数器计时器脚本。就在 id="counter" 段落之后,而不是这段代码:

<body>

<p> beginning of site</p>

<table id="timer_table">
    <tbody>
        <tr>
            <td>
                <p id="counter"  style="color: red;"> Here's the counter: </p>

            </td>
        </tr>
    </tbody>
</table>

<p> rest of site...</p>

</body>

我会得到这个代码:

<body>

<p> beginning of site</p>

<table id="timer_table">
    <tbody>
        <tr>
            <td>
                <p id="counter"  style="color: red;"> Here's the counter: </p>
                <script>
                    var myCountdown1 = new Countdown({time:316});
                </script>
            </td>
        </tr>
    </tbody>
</table>

<p> rest of site...</p>

</body>

我通过使用萤火虫控制台来做到这一点,我正在运行这个:(写在不能附加 <script> 元素,很难,它仍然不能很好地工作)

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "js_folder/js1.js";
$('#counter').after(script);

js1.js 很简单:

var myCountdown1 = new Countdown({time:316});

效果不好。而不是得到这个结果: http ://bit.ly/19Ve9oM 我得到了这个: http: //postimg.org/image/np8y4spbx/

当我尝试检查页面源时,我什么也没得到。

总结一下:我应该使用哪个 jquery commnad 来插入

                <script>
                    var myCountdown1 = new Countdown({time:316});
                </script>

在 id="counter" 段落之后?并且它会像原来的 html 中已经写了这一行一样工作

谢谢

4

1 回答 1

0

如果脚本编写得当,脚本的初始化位置应该无关紧要。大多数脚本应该在页面底部加载,以加快浏览器渲染 DOM 的时间,因为脚本标签是阻塞的,除非它们的async属性设置为true.

要使用 jQuery 加载脚本,您可以使用处理程序中的jQuery.getScript方法jQuery.ready来确保在 DOM 准备好之前不会执行代码。在您的情况下,它看起来像这样:

// This is a shorthand for jQuery.ready
$(function(){
    $.getScript("js_folder/js1.js");
});

上面的代码片段应该添加到文档底部的脚本标记中(由于我已经说明的原因),但可以在任何地方工作。

但是,考虑到js_folder/js1.js您的内容,不如将其放在.ready处理程序中。比如这样:

$(function(){
    var myCountdown1 = new Countdown({time:316});
});
于 2013-06-20T16:44:20.090 回答