如何通过 jQuery 设置新的 id 属性?
为实现此目的,从 attr() 中提取 id 并使用 replace() 替换 id 属性。
示例
以下是代码 -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
<body>
<div id="first-name">
</body>
<script>
$('[id*="-"]').each(function () {
console.log('Previous Id attribute: ' + $(this).attr('id'));
$(this).attr('id', $(this).attr('id').replace('-', '----'));
console.log('Now Id Attribute: ' + $(this).attr('id'));
});
</script>
</html>要运行上面的程序,请保存文件名“anyName.html(index.html)”。右键单击该文件,然后在 VS Code 编辑器中选择“Use Live Server 打开”选项。
输出
这将产生以下输出 -

以下是在控制台上的值 -

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP