首先,我已经阅读了Can't append <script> element , 在阅读它并利用它所说的内容之后,我达到了 一个不同的问题:是的,它向我展示了如何插入脚本标签,但是当它插入时 它“删除”页面的其余部分:
我想使用 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>
添加脚本的地方会显示新的倒计时。 我通过使用 Firebug 控制台来做到这一点,我正在运行这个:(如 Can't append <script> element 中所写, 很难,它仍然不能正常工作)
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 在 id="counter"段落之后插入倒计时? 并且它会像原始 html 中已经写入了这一行一样工作。
此外,我无权访问页面的 html 源代码。如果我有,我会自己添加它,它会很好用,就像第一个图片链接中所示。因此我不得不使用 Jquery。
您可以在这里尝试一下(使用第二个链接进行尝试):
这就是我想要的:http://jsfiddle.net/JxLwM/
但是用 jquery 来做:http://jsfiddle.net/F5rwK/5/
注意,在第二个链接中,尝试放置
var myCountdown1 = new Countdown({time:316});
在 ss1 中,看看会发生什么。 谢谢。
最佳答案
与其尝试插入脚本标签,不如使用倒计时计时器中的代码将其插入正确的位置。参见 http://jsfiddle.net/F5rwK/7/对于工作示例。
关键部分是向您的 HTML 添加一个容器(在示例中,它是 ID 为 target_location
的 div
。
这样HTML就变成了(运行JS代码插入div后)
<body>
<p> beginning of site</p>
<table id="timer_table">
<tbody>
<tr>
<td>
<p id="counter" style="color: red;"> Here's the counter: </p>
<div id="target_location"></div>
</td>
</tr>
</tbody>
</table>
<p> rest of site...</p>
</body>
然后是 JS(添加新的 div 然后运行倒计时)
$('#counter').after('<div id="target_location"></div>');
var myCountdown1 = new Countdown({time:316, target:'target_location'});
关于javascript - 添加倒计时,使用 jquery。弄乱了页面。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226385/