我对这段代码有疑问:
$(document).ready(function() {
sweetAlert("a");// This is just a test, and it runs successfully by the way!!!
});
$("#login").keyup(check);
function check() {
$(this).val($(this).val().replace(/\s/g,"_"));
}
浏览器正在加载文件,我从检查器中检查了它,并且它运行了 .ready 脚本。但它不适用于 .keyup。然后当我复制/粘贴该行时
$("#login").keyup(check);
在控制台中它成功运行。
如果需要,这里是 html 表单:
<input type="text" name="login" id="login"/>
感谢您的帮助。
最佳答案
只需将 .keyup
移至 document
就绪函数中即可:
$(document).ready(function() {
sweetAlert("a");// This is just a test, and it runs successfully by the way!!!
$("#login").keyup(check);
});
原因是,无论你在 $(document).ready(function() {
) 中编写的任何代码,只有在加载所有 DOM 元素后才会执行。当你说它不起作用时,当 $("#login").keyup(check);
执行时,#login
不会加载。$(document).ready(function () {
一旦所有元素加载完毕,就会为您执行。无论控制台中执行什么,都会在文档完全加载后执行。
关于javascript - jQuery 脚本在控制台中运行,但不在文件中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34456621/