The difference between html(), text() and val() of jQuery


The difference between the three

html(): It can be set to get the start tag and end tag 内容, which is the same as the dom attribute innerHTML.

text(): You can also set and get the start tag and end tag 文本, just like the dom attribute innerText.

val(): 表单项The value attribute value that can be set and obtained is the same as the dom attribute value. The val method can also set the selected state of multiple form items at the same time (single selection, multiple selection, and drop-down are all available).

Let's explain in detail with code

1. HTML usage

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="jquery-3.5.1.js"></script>
		<script type="text/javascript">
		
			$(function(){
      
      
				alert($("div").html()) //获取内容
				
				$("div").html('<div>我是小军</div>')//设置内容
				
			})
		</script>
	</head>
	<body>
		<div id='btn'>大家好<span>我是小明</span></div>
	</body>
</html>

operation result
insert image description here
insert image description here

2. Text() usage

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="jquery-3.5.1.js"></script>
		<script type="text/javascript">
		
			$(function(){
      
      
				alert($("div").text()) //获取内容
				
				$("div").text('<div>我是小军</div>')//设置内容
				
			})
		</script>
	</head>
	<body>
		<div id='btn'>大家好<span>我是小明</span></div>
	</body>
</html>

operation result

insert image description here
insert image description here

3. val usage

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="jquery-3.5.1.js"></script>
		<script type="text/javascript">
		
			$(function(){
      
      
				alert($("#textid").val()) //获取内容
				
				$("#textid").val('我是小军')//设置内容
				
			})
		</script>
	</head>
	<body>
		<input type="text" id="textid" value="我是小明" />
	</body>
</html>

operation result
insert image description here
insert image description here

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="jquery-3.5.1.js"></script>
		<script type="text/javascript">
		
			$(function(){
      
      
				
				$(":checkbox").val(["checkbox1","checkbox2"])  //选中两个
				
			})
		</script>
	</head>
	<body>
		<input type="checkbox" />checkbox1
		<input type="checkbox" />checkbox2
		<input type="checkbox" />checkbox3
	</body>
</html>

operation result
insert image description here

Guess you like

Origin blog.csdn.net/Tom197/article/details/119823352