这个问题在SO中已经问了很多遍了。我通读了许多这些答案,但找不到正确的解决方案。问题在于,js是在单独的文件中定义的,该文件在页面的head
部分中加载,但是调用此文件中的函数时,js会提示ReferenceError。最奇怪的是,与文件不同的功能在另一页中起作用。
头的样子:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="mysecrettokenissecret">
<link rel="stylesheet" href="http://webpage.local:8000/css/app.css">
<link rel="stylesheet" href="http://webpage.local:8000/css/additional.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script type="text/javascript" src="http://webpage.local:8000/js/app.js"></script>
<script type="text/javascript" src="http://webpage.local:8000/js/additional.js"></script>
</head>
文件出现问题:
function op_check(an_array)
{
var score = 0;
for(i=0; i<an_array.length; i++)
{
if(an_array[i] != null)
{ score++; }
}
if(score > 0)
{ return true; }
else
{ return false; }
}
function setCookie(cookie_name, cookie_value, expiration_interval)
{
var date = new Date()
date.setTime(date.getTime() + (expiration_interval*24*60*60*1000));
var expires = "expires=" + date.toUTCString();
document.cookie = cookie_name + "=" + cookie_value + ";" + expires + ";path=/";
}
function getCookie(cookie_name)
{
var name = cookie_name + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) == ' ')
{ c = c.substring(1); }
if (c.indexOf(name) == 0)
{ return c.substring(name.length, c.length); }
}
return "";
}
function checkCookie(cookie_name)
{
var cookie_value = getCookie(cookie_name);
if (cookie_value == "")
{ return false; }
else if(cookie_value == "true")
{ return true; }
else
{ return "Something went wrong."; }
}
function agree_button_click()
{
setCookie("cookie_law", true, 365);
}
body
中的脚本,该脚本应调用checkCookie
函数。
<script>
$(document).ready(function(){
var cookie_law_exists = checkCookie("cookie_law");
var cookie_law_value = getCookie("cookie_law")
if(cookie_law_exists == false || cookie_law_value == false)
{
$('#cookieRODOModal').modal('show')
}
else
{
$('#cookieRODOModal').modal('hide')
}
function change_example_url()
{
var urls = [
'not important 1',
'not important 2'
]
var max = urls.length;
var roll = Math.floor(Math.random() * (max + 1));
$("#example_url").text(urls[roll]);
}
var new_url;
new_url = setInterval(change_example_url, 5000);
});
</script>
谢谢您的帮助。
编辑-错误消息:
app.js:1 jQuery.Deferred exception: checkCookie is not defined
ReferenceError: checkCookie is not defined
at HTMLDocument.<anonymous> (http://webpage.local:8000/:38:37)
at c (http://webpage.local:8000/js/app.js:1:52675)
at l (http://webpage.local:8000/js/app.js:1:52977) undefined