我的JavaScript不起作用

My JavaScript isn't working

本文关键字:不起作用 JavaScript 我的      更新时间:2023-09-26

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="hello.js"></script>
    <title>Title</title>
</head>
<body>
  <form action="#">
    <p>Name:<input type="text"/></p>
    <p>Password:<input type="text"/></p>
    <p><input id= "newsletter_button"type="button" value="CLICK ME"/></p>
  </form>
</body>
</html>

这是JavaScript:

$(":text").focusin(function () {
  $(this).css("background-color", "red");
});
$(":text").blur(function() {
  $(this).css("background-color", "#fff");
});

hello.js和index.html在同一个文件中。我觉得jQuery有问题

要么把hello.js放在</body>之前,要么用

$(document).ready(function(){
$(":text").focusin(function () {
  $(this).css("background-color", "red");
});
$(":text").blur(function() {
  $(this).css("background-color", "#fff");
});
});

它的作用是在加载整个页面时执行代码。否则,如果你把它放在":text" DOM对象加载之前,它会遇到DOM对象未定义错误。

还有一个标记错误

<p><input id= "newsletter_button"type="button" value="CLICK ME"/></p>

在文字前加空格

<p><input id= "newsletter_button" type="button" value="CLICK ME"/></p>