标签:console 读取 name js user data id log
标签上有两个属性data-id
和 data-user-name
, 需要通过js去获取
1
2
3
4
5
6
7
8
9
|
<style>
#user::before {
content: attr(data-id);
}
#user::after {
content: attr(data-user-name);
}
</style>
<div id= "user" data-id= "666" data-user-name= "Tom" ></div>
|
方式一:dataset
1
2
3
4
5
6
7
8
9
10
11
12
13
|
let user = document.querySelector( "#user" );
console.log(user.dataset.id);
console.log(user.dataset.userName);
user.dataset.id = 777;
user.dataset.userName = "Jack" ;
user.dataset.age = 23;
delete user.dataset.userName;
|
方式二: getAttribute/setAttribute/removeAttribute
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
let user = document.querySelector( "#user" );
console.log(user.getAttribute( "data-id" ));
console.log(user.getAttribute( "data-user-name" ));
console.log( typeof user.getAttribute( "data-id" ));
user.setAttribute( "data-id" , 777);
user.setAttribute( "data-age" , 23);
user.removeAttribute( "data-user-name" );
|
方法三:jQuery.attr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<script src= "https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<script>
let user = $( '#user' );
console.log(user.attr( "data-id" ));
console.log(user.attr( "data-user-name" ));
user.attr( "data-id" , 777);
user.attr( "data-age" , 23);
user.removeAttr( "data-user-name" );
</script>
|
方法四:jQuery.data
注意:$.data()的值进行修改并不会影响到DOM元素上的data-*属性的改变
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<script src= "https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<script>
let user = $( "#user" );
console.log(user.data( "id" ));
console.log(user.data( "user-name" ));
user.data( "id" , 777);
user.data( "age" , 23);
user.removeData( "user-name" );
console.log(user.data());
</script>
|
标签:console,
读取,
name,
js,
user,
data,
id,
log
From: https://www.cnblogs.com/QunShan/p/16883573.html