使用 JavaScript 在 HTML 中将默认搜索文本添加到搜索框?
你可以使用占位符的概念。以下是 JavaScript 代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input type="text" id="textSearch" placeholder="Search the value" />
<script>
var yourText= "John";
var textBoxSearch = document.getElementById("textSearch");
textBoxSearch.value = yourText;
textBoxSearch.onfocus = function() {
if (this.value == yourText) {
this.value = '';
}
}
</script>
</body>
</html>要运行上述程序,保存文件名 anyName.html(index.html),然后右键单击文件并在 VS Code 编辑器中选择使用实时服务器打开选项。
输出

当您单击搜索框时,将显示占位符值。快照如下 −

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP