事件委托
根据数组中图片的数量动态生成按钮,点击相应的按钮出现相应的图片
方法1
<body>
<div id="control">
</div>
<img src="" alt=""/>
<script>
var pictures = ['../images/cat.jpg','../images/cat2.jpg','../images/cat3.jpg','../images/cat4.jpg','../images/girl.jpg'];
var control = document.getElementById('control');
var img = document.getElementsByTagName('img')[0];
img.src = pictures[0];
pictures.forEach(function (src, index) {
var btn = document.createElement('button');
btn.innerText = `change${index}`;
control.appendChild(btn);
btn.onclick = function(){
img.src = src;
}
})
</script>
</body>
方法2
<body>
<div id="control">
</div>
<img src="" alt=""/>
<script>
var pictures = ['../images/cat.jpg','../images/cat2.jpg','../images/cat3.jpg','../images/cat4.jpg','../images/girl.jpg'];
var control = document.getElementById('control');
var img = document.getElementsByTagName('img')[0];
img.src = pictures[0];
pictures.forEach(function (src, index) {
var btn = document.createElement('button');
btn.innerText = `change${index}`;
control.appendChild(btn);
//给按钮添加一个自定义属性
btn.dataset.src = src;
});
//采用事件委托的方式
control.onclick = function (e) {
if(e.target.dataset.src){
img.src = e.target.dataset.src;
}
}
</script>
<!--<script src="demon.js"></script>-->
</body>
``