如何用jQuery禁止浏览器对输入字段进行自动填充
在这篇文章中,我们将看到如何禁用浏览器对输入字段的自动填充属性。为此,我们创建了一个HTML页面,其中导入了jQuery CDN以使用jQuery,并编写了它的代码。
步骤:
- 创建一个基本的HTML页面,其中至少有一个带有 “id “属性的输入字段。
- 从脚本标签导入jQuery CDN,在页面上使用jQuery。
- 然后在脚本标签中写上jQuery代码,用于禁用输入字段的自动填充功能。
为了实现这一点,我们使用jQuery的两种方法来设置属性值的字段:
- attr() 方法
- prop() 方法
例子1:使用attr()方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width,initial-scale=1.0">
<!-- Import jQuery cdn library -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
// Execute this code when page is
// totally loaded
(document).ready(function () {
/* Setting the autocomplete of
input field to off to make
autofill to disable */
("#name").attr("autocomplete", "off");
});
</script>
</head>
<body>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
</body>
</html>
输出:
这将是代码的输出
例子2:使用prop()方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Disable Autofill</title>
<!-- Import jQuery cdn library -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
// Execute this code when page is
// totally loaded
(document).ready(function () {
/* Setting the autocomplete of
input field to off to make
autofill to disable */
("#name").prop("autocomplete", "off");
});
</script>
</head>
<body>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
</body>
</html>
输出:
代码的输出。在这个领域,没有自动填写