• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何使用jQuery更改元素id?

jquery 搞代码 4年前 (2021-12-27) 60次浏览 已收录 0个评论

在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>
				<<p style="color:transparent">来源gao!%daima.com搞$代*!码网</p>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>

以上就是如何使用jQuery更改元素id?的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何使用jQuery更改元素id?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址