尝试使用JavaScript将图像源从images / small /更改为images / medium /
我尝试过以下代码,但由于某些原因,点击事件未被提取,感谢您提供任何帮助。
的Javascript
var thumbs = document.getElementById("thumbnails");
thumbs.addEventListener("click", function (i) {
if (i.target.nodeName.toLowerCase() == "img") {
// get image filename of clicked thumbnail
var clickedImageSource = i.target.src;
// replace the folder name of the image
var newSrc = clickedImageSource.replace("small","medium");
}
});
HTML
<div id="thumbnails">
<img src="images/small/Home.jpg" title="Home" />
<img src="images/small/Office.jpg" title="Office" />
<img src="images/small/Park.jpg" title="Park" />
<img src="images/small/Hills.jpg" title="Hills" />
<img src="images/small/HaveEyes.jpg" title="HaveEyes" />
</div>
答案 0 :(得分:2)
在DOM元素可用之前,您无法附加事件侦听器。
<script>
// executed before dom is ready.
var thumbs = document.getElementById("thumbnails");
thumbs.addEventListener("click", function(i) {
console.log('clicked');
});
</script>
<div id="thumbnails">
<img src="images/small/Home.jpg" title="Home" />
<img src="images/small/Office.jpg" title="Office" />
<img src="images/small/Park.jpg" title="Park" />
<img src="images/small/Hills.jpg" title="Hills" />
<img src="images/small/HaveEyes.jpg" title="HaveEyes" />
</div>
<script>
// executed after dom is ready.
var thumbs = document.getElementById("thumbnails");
thumbs.addEventListener("click", function(i) {
console.log('clicked');
});
</script>
&#13;