【发布时间】:2016-08-07 15:33:08
【问题描述】:
我用 javascript 构建了我的脚本,然后决定将其转换为 jQuery 以简化未来的功能。当我在脚本周围添加 .ready 时,我的函数不再可见。根据我对 .ready 如何工作的理解,它的内容应该只在创建 DOM 后触发。所以我希望看到console.log(userInput) 的结果——出于示例目的,我已经取出了大部分代码。但是当我运行程序时,firebug 显示“ReferenceError: getInput is not defined”。
这是我的html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="script/script.js"></script>
</head>
<body>
<form>
Input: <input type="text" name="userInput" id="userInput" autofocus><br>
<input type="button" value="Submit" name="Submit" onclick="getInput()">
</form>
</body>
</html>
这是我的脚本:
$(document).ready(function() {
function getInput() {
var userInput = $('#userInput').val();
console.log(userInput);
}
});
如果我删除 .ready 函数,一切都会按预期工作,但我不确定为什么会发生冲突。我读了这篇文章 (What exactly does $(document).ready guarantee?),其中提到了添加一个 onload 函数,我尝试过,但仍然遇到同样的错误。
为什么 .ready 会导致冲突?我不需要它,但它对我来说仍然没有意义。有人可以解释问题是什么或指向我解释它的帖子吗?
【问题讨论】:
-
从哪里调用
getInput?
标签: javascript jquery