本教程操作环境:windows7系统、jquery3.6.0版本、dell g3电脑。
jquery赋值有三种方法:
text()
html()
val()
text() 方法
text() 方法可以设置被选元素的文本内容。
语法:
//设置文本内容:$(selector).text(content)//使用函数设置文本内容:$(selector).text(function(index,currentcontent))
示例:给div赋值
<!doctype html><html> <head> <meta charset="utf-8" /> <script src="./js/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").text("hello world!"); }); }); </script> </head> <body> <div style="width: 200px;height: 100px;border: 1px solid #afeeee; background-color: #afeeee;"></div><br> <button>给div添加内容</button> </body></html>
html() 方法
html() 方法可以设置被选元素的内容(innerhtml)。
语法:
//设置内容:$(selector).html(content)//使用函数设置内容:$(selector).html(function(index,currentcontent))
示例:给p赋值
<!doctype html><html> <head> <meta charset="utf-8" /> <script src="./js/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").html("hello world!"); }); }); </script> <style> p{ width: 200px; height: 100px; border: 1px solid #afeeee; background-color: #afeeee; } </style> </head> <body> <p></p> <button>给p添加内容</button> </body></html>
val() 方法
val() 方法设置被选元素的 value 属性,一般用于input输入框的赋值。
语法:
//设置 value 属性:$(selector).val(value)//通过函数设置 value 属性:$(selector).val(function(index,currentvalue))
示例:给input元素赋值
<!doctype html><html> <head> <meta charset="utf-8" /> <script src="./js/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("input").val("hello world!"); }); }); </script> <style> p{ width: 200px; height: 100px; border: 1px solid #afeeee; background-color: #afeeee; } </style> </head> <body> <input type="text"><br><br> <button>给input添加内容</button> </body></html>
【推荐学习:jquery视频教程、web前端视频】
以上就是jquery有几种赋值方式的详细内容。