![](/img/trans.png)
[英]How do i get a variable from an inline js script in html and put it into an external .js file?
[英]Should I convert my inline script so I can put it into an external .js file?
我是 jQuery 的新手,我一直在我的网页中使用 koga73 ( https://github.com/koga73/SnapScroll ) 的 SnapScroll jQuery 插件。
它要求我使用内联脚本:
<script>
var snapScroll = $("header, section, footer").SnapScroll({
hashes:true }); console.log(snapScroll);
$("header").on(snapScroll.eventChangeActive, function(evt, newActive){
console.log(evt, newActive);
});
$(document).on(snapScroll.eventChangeVisible, function(evt, visibleList){
console.log(evt, visibleList.data);
});
</script>
它一直工作正常,但我只是想知道是否值得将其移动到外部 .js 文件中,如果是这样,我如何将代码转换为在外部 .js 文件中工作?
我的外部js文件是:
<script type="text/javascript" src="web/js/init.js"></script>
通常,您希望将所有 JavaScript 放在外部文件中 - 内联对于调试和开发非常有用,但是当您进入生产环境时,始终是一个已经缩小和压缩的外部文件 - 不过,您可以稍后再担心最后两个.
如果你将该代码放在一个文件中,你想像这样放置该代码......并丢失脚本标签
// A $( document ).ready() block.
$(document).ready(function() {
var snapScroll = $("header, section, footer").SnapScroll({
hashes:true }); console.log(snapScroll);
$("header").on(snapScroll.eventChangeActive, function(evt, newActive){
console.log(evt, newActive);
});
$(document).on(snapScroll.eventChangeVisible, function(evt, visibleList){
console.log(evt, visibleList.data);
});
});
//OR
// Shorthand for $( document ).ready()
$(function() {
//your code here
});
然后,在页面底部插入您的外部脚本链接。
您可以将标签内的行粘贴到 js 文件中。 您不需要在 js 文件中使用 script 标签。 就是这样。 无论您是将代码内联还是放在外部 js 文件中,这实际上是您的偏好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.