由于元素内容可分为文本内容和HTML内容,那么对元素的操作也可以分为对文本内容操作和对HTML内容操作。
1.对元素内容进行操作
text():获取匹配元素内部的文本内容
text(val):设置匹配元素内部的文本内容
2.对HTML内容操作
html():获取匹配元素内部的html代码
html(val):设置匹配元素内部的html代码
3.对元素值操作
val():用于获取第一个匹配元素的当前值
val(val):用于设置所有匹配元素的值
Demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#setUserName{
margin-bottom: 50px;
}
</style>
<script src="../../js/jquery.min.js"></script>
<script>
$(function(){
console.log($(".content").html());//获取元素内部的html代码
$(".content").html("<div class='innerContent'>年轻人,必须搞起来!</div>");//设置元素内部的html代码
console.log($(".content").text());//获取元素内部的文本内容
$(".content").text('try!try!try!');//设置元素内部的文本内容
//对元素的值进行操作
/*
val()方法:用于获取第一个匹配元素的当前值
val(value)方法:用于设置所有匹配元素的值
*/
$('#username').on('change',function(){
console.log($(this).val());
});
$('#setUserName').on('click',function(){
$('#username').val('jack bryant');//设置元素的值
});
});
</script>
</head>
<body>
<button id="setUserName">设置用户名</button>
<form action="">
用户名: <input type="text" id="username"><br>
密码:<input type="password" id="pwd">
</form>
<div class="content">
<p>I want to marry you,my baby!</p>
<p>Come On!young boy!</p>
</div>
</body>
</html>