[英]Javascript function is not defined in script?
I know this question has been asked before but I have tried numerous solutions from stackoverflow and I could not find the problem.I receive the error in the browser console that the function that I defined in the script tag is not defined.This is the code:我知道以前有人问过这个问题,但我尝试了 stackoverflow 的许多解决方案,但我找不到问题。我在浏览器控制台中收到错误,我在脚本标签中定义的函数未定义。这是代码:
<html>
<body>
<input type="text" id="input_1"/>
<button type="button" value="Click" onclick="cd()" id="getDatabaseData">Click!</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
function cd() {
var inbtn = {};
inbtn.input = $('#input_1').val();
console.log('Started...');
$.ajax({
type: 'post',
url: '<%: Url.Action("Trial") %>',
data: inbtn,
success: function er() {
console.log("Succes!")
},
error: function err() {
console.log("Error!")
}
})
}
</script>
</body>
</html>
I tried to add $document.ready and also to add a separate event listener(not onclick function)我尝试添加 $document.ready 并添加一个单独的事件侦听器(不是 onclick 函数)
$(document).ready(
document.getElementById("getDatabaseData").addEventListener("click", cd, false));
It did not worked.I also replaced the whole function with a simple function:它没有用。我还用一个简单的函数替换了整个函数:
function cd(){
console.log("Message");
}
and I still receive the same error:我仍然收到同样的错误:
Uncaught ReferenceError: cd is not defined
at HTMLButtonElement.onclick
Just a small mistake只是一个小错误
You need to make another script tag and put the function cd inside您需要制作另一个脚本标签并将函数 cd 放在里面
<html>
<body>
<input type="text" id="input_1"/>
<button type="button" value="Click" onclick="cd()" id="getDatabaseData">Click!</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function cd() {
var inbtn = {};
inbtn.input = $('#input_1').val();
console.log('Started...');
$.ajax({
type: 'post',
url: '<%: Url.Action("Trial") %>',
data: inbtn,
success: function er() {
console.log("Succes!")
},
error: function err() {
console.log("Error!")
}
})
}
</script>
</body>
</html>
I am assuming this is the result you want , because the cd is now defined我假设这是您想要的结果,因为现在定义了 cd
To clarify what has already been said, but not specifically called out... a script
tag can EITHER contain a src
attribute to pull in an external script file OR it can contains the script content.为了澄清已经说过的内容,但没有特别指出......
script
标签可以包含一个src
属性来拉入外部脚本文件,或者它可以包含脚本内容。 A single script
tag cannot contain both.单个
script
标记不能同时包含两者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.