在 jQuery 中设置输入值
val()
方法可以在 jQuery 中用于设置 jQuery 中输入字段的值。本教程演示如何使用 val()
方法在 jQuery 中设置输入字段的值。
在 jQuery 中设置输入值
val()
是 jQuery 中的内置方法,用于返回或设置给定元素的值。如果此方法返回值,那将是第一个选定元素的值。
如果此方法用于设置元素的值,则可以为一个或多个元素设置该值。该方法可以以三种不同的方式使用。
让我们有一个简单的例子来返回输入字段的值。
示例代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> jQuery Val() Method</title>
<style>
p {
color: green;
margin: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<input type="text" placeholder="Type Something">
<p></p>
<script>
$( "input" ).keyup(function() {
var Input_Value = $( this ).val();
$( "p" ).text( Input_Value );
}).keyup();
</script>
</body>
</html>
上面的代码将返回输入字段的值并将其写入给定的段落。
输出:
现在让我们尝试使用 val()
方法设置输入字段的值。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery val() Method</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#DemoInput").val("https://www.jiyik.com/");
});
</script>
</head>
<body>
<h1> jQuery Val() Method</h1>
<label>Enter Your Site:</label>
<input type="text" id="DemoInput">
</body>
</html>
上面的代码会将给定输入的值设置为 https://www.jiyik.com/
。
让我们使用带有函数的 val()
方法。
示例代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery val() Method</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<h1> jQuery Val() Method</h1>
<p>Type anything and it will be converted into Uppercase.</p>
<p>Type and click outside.</p>
<input type="text" placeholder="type anything">
<script>
$( "input" ).on( "blur", function() {
$( this ).val(function( x, Input_Value ) {
return Input_Value.toUpperCase();
});
});
</script>
</body>
</html>
上面的代码会将输入字段的值转换为大写。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。