将内联javascript移动到外部文件

时间:2018-03-14 09:21:25

标签: javascript html

尝试进行Chrome扩展,但不允许使用内联JS

<script type="text/javascript">
function one() {
    window.location.href='https://youtube.com/feed/subscriptions';
}

var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").textContent = days[d.getDay()];
</script>

这就是我的内联js 我将其转换为:

function one() {
window.location.href='https://youtube.com/feed/subscriptions';
}
document.getElementById('linkOne').onclick = one;  

var d = new Date();
var days = 
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").textContent = days[d.getDay()];  

chrome不会允许你调用外部js函数,即&#34; one()&#34;因为它属于内联js
我尝试使用文本&#39; linkOne&#39;来调用该函数。相反,但无济于事

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

我不知道你为什么使用location.href转发到另一个页面,在你的情况下,这可以通过一个简单的<a href="...">来完成。

我写了一个小的html标记,并将你的js源文件放在foo.js

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <!-- your demo content -->
    <div id="demo"></div>
    <!-- your link -->
    <a href="#" id="linkOne">link</a>
    <!-- your js file -->
    <script src="foo.js"></script>
</body>
</html>