val()方法是jQuery中的一个内置方法,用于返回或设置所选元素的属性值。此方法适用于HTML表单元素。 语法: 使用该方法有三种方法,如下所示:
null
$(selector).val()
- 参数: 此方法不接受任何参数。
$(selector).val(value)
- 参数: 此方法接受单个参数 价值 这是强制性的。它用于指定属性的值。
$(selector).val(function(index,current_value))
- 参数: 此方法接受单个参数 作用 这是可选的。它包含元素的索引位置和所选元素的当前值属性。
返回值: 此方法返回由val()方法进行指定更改的选定元素。 下面的示例演示了jQuery中的val()方法: 例1:
html
<!DOCTYPE html> < html > < head > < title >The val Method</ title > < script src= </ script > <!-- jQuery code to show the working of this method --> < script > $(document).ready(function() { $("button").click(function() { $("input:text").val("GeeksforGeeks!"); $("input:text").css("color", "green"); $("input:text").css("font-size", "40px"); $("input:text").css("font-weight", "bold"); $("input:text").css("font-family", "times new roman"); }); }); </ script > < style > div { background-color: lightgreen; padding: 20px; width: 41%; min-height: 150px; border: 2px solid green; } input { border: 2px solid green; padding-left: 15px; width: 350px; height: 80px; } </ style > </ head > < body > < div > < p > < input type="text" name="user"> </ p > <!-- click on this paragraph and see the change --> < button >Click Here!</ button > </ div > </ body > </ html > |
输出:
例2: 该方法采用两个值,第一个值表示索引位置,第二个值表示属性值。无需传递索引位置,函数将自动设置为null(n=0),且“c”指定输入字段的当前值。
html
<!DOCTYPE html> < html > < head > < title >The val Method</ title > < script src= </ script > <!-- jQuery code to show the working of this method --> < script > $(document).ready(function() { $("button").click(function() { $("input:text").val(function(n, c) { return c + " GeeksforGeeks!"; }); }); }); </ script > < style > div { background-color: lightgreen; padding: 20px; width: 300px; height: 80px; border: 2px solid green; } input { border: 2px solid green; padding-left: 15px; width: 220px; font-weight: bold; height: 30px; } </ style > </ head > < body > < div > < p > < input type="text" name="user" value="Welcome To"> </ p > <!-- click on this paragraph and see the change --> < button >Click Here!</ button > </ div > </ body > </ html > |
输出: 单击按钮之前:
点击按钮后:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END