本篇内容介绍了“jquery赋值的方式有哪些”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
jquery有3种赋值方式:1、使用text(),语法“$(selector).text(content)”,可以设置被选元素的文本内容。2、使用html(),语法“$(selector).html(content)”,可以设置被选元素的内容(innerHTML);3、使用val(),可以设置被选元素的value属性,一般用于input输入框的赋值。
本教程操作环境: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赋值的方式有哪些”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。