×

在jQuery中使用一些内置方法来更改元素id

作者:andy0012019.09.05来源:Web前端之家浏览:8894评论:0
关键词:js

在jQuery中可以使用一些内置方法来更改元素id,下面本篇文章就来给大家介绍一下使用jQuery更改元素id的方法,希望对大家有所帮助。

方法1:jQuery attr()方法

attr()方法设置/返回选定元素的属性和值。如果此方法用于返回属性值,则返回第一个选定元素的值。如果此方法用于设置属性值,则为所选元素集设置一个或多个属性/值对。

示例:使用attr()方法更改元素的ID

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<style>
			#myCol {
				background: green;
			}
			
			#newID {
				background: palevioletred;
			}
			
			table {
				color: white;
			}
			
			td {
				padding: 10px;
			}
		</style>
	</head>

	<body>
		<center>
			<table>
				<colgroup>
					<col id="myCol" span="3">
					<col style="background-color:green">
				</colgroup>

				<tr>
					<th>S.No</th>
					<th>Title</th>
					<th>id</th>
				</tr>
				<tr id="row1">
					<td>No.1</td>
					<td>Hello</td>
					<th>id_1</th>
				</tr>
				<tr>
					<td>No.2</td>
					<td>Hi</td>
					<th>id_2</th>
				</tr>
			</table>
			<br>

			<button onclick="Geeks()">单击</button>

		</center>
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
		<script>
			function Geeks() {
				$("col").attr('id', 'newID');
			}
		</script>
	</body>

</html>

方法2:jQuery prop()方法

prop()方法设置/返回匹配元素的属性和值。如果此方法用于返回属性值,则返回第一个选定元素的值。如果此方法用于设置属性值,则它为所选元素集设置一个或多个属性/值对。

示例:使用prop()方法更改元素的ID

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<style>
			#myCol {
				background: lightcoral;
			}
			
			#newID {
				background: palevioletred;
			}
			
			table {
				color: white;
			}
			
			td {
				padding: 10px;
			}
		</style>
	</head>

	<body>
		<center>
			<table>
				<colgroup>
					<col id="myCol" span="3">
					<col style="background-color:lightcoral">
				</colgroup>

				<tr>
					<th>S.No</th>
					<th>Title</th>
					<th>id</th>
				</tr>
				<tr id="row1">
					<td>No.1</td>
					<td>Hello</td>
					<th>id_1</th>
				</tr>
				<tr>
					<td>No.2</td>
					<td>Hi</td>
					<th>id_2</th>
				</tr>
			</table>
			<br>

			<button onclick="Geeks()">单击</button>

		</center>
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
		<script>
			function Geeks() {
				$("col").prop('id', 'newID'); 
			}
		</script>
	</body>

</html>

介绍了2种方法,预览看下效果吧。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js8209348092384028309.html

网友评论文明上网理性发言 已有0人参与

发表评论: