JS中遍历对象的方法
- for…in方法
- Object.keys(obj) Object.values(obj)
-
obj:要返回其枚举自身属性的对象
-
返回值:一个表示给点对象的所有属性的键或值得数组
-
- 使用Object.getOwnProjectyNames(obj)
- 返回一个数组,包含自身所有属性(包括不可枚举的属性)
- 遍历可以获取key和value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>何须执手问年华</title>
</head>
<body>
<script>
var obj = {
id:100001,
name:"小明",
salary:11111,
hobby:"play basketball",
play:function () {
console.log(this.name+"like"+this.hobby)
},
}
/*1、for...in遍历*/
for(var key in obj){
console.log(obj[key])
}
obj.play()
/*2、Object.keys(obj) Object.values(obj)
* obj:要返回其枚举自身属性的对象
*
* 返回值:一个表示给点对象的所有属性的键或值得数组
* */
console.log(Object.keys(obj)) //属性名
console.log(Object.values(obj)) //属性值
/*3、使用Object.getOwnProjectyNames(obj)
* 返回一个数组,包含自身所有属性(包括不可枚举的属性)
* 遍历可以获取key和value
* */
Object.getOwnPropertyNames(obj).forEach(key){
console.log(key+":"+obj[key])
}
</script>
</body>
</html>
点击小图切换大图
js 中点击用.onclick
下面是将最后一张图转换成上面所给的图片
通过类名class来改变img标签的内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>何须执手问年华</title>
<style>
/*css选择器 选择前四个-n+4
注意:不要4-n css不识别4-n 只知道+
*/
img:nth-of-type(-n+4){
width: 200px;
height: 200px;
float: left;
}
</style>
</head>
<body>
<img src="images/001.jpg" alt="">
<img src="images/002.jpg" alt="">
<img src="images/003.jpg" alt="">
<img src="images/005.jpg" alt="">
<div style="clear: both"></div>
<img src="images/placeholder.png" alt="" class="place">
<script>
window.onload = function () {
var imgs = document.querySelectorAll('img:nth-of-type(-n+4)');
console.log(imgs)
var placeHodler = document.querySelector('.place');
for(var i = 0;i<imgs.length;i++){
imgs[i].onclick = function () {
var luJing = this.src;
console.log(luJing)
placeHodler.style.width = '400px'
placeHodler.style.height = '400px'
placeHodler.src = luJing ;
}
}
}
</script>
</body>
</html>
js中的排他思想
先设置四个盒子
然后通过点击onclick改变盒子的BackgroundColor
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Raines</title>
<style>
div {
width: 200px;
height: 200px;
background-color: deepskyblue;
float: left;
margin-left: 50px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
var divs = document.getElementsByTagName('div')
for(var i =0;i<divs.length;i++){
divs[i].onclick = function () {
/*先全部变成上面默认背景色*/
for(var j =0;j<divs.length;j++){
divs[j].style.backgroundColor ='deepskyblue'
}
this.style.backgroundColor = 'yellow'
}
}
</script>
</body>
</html>