javascript - Using vanilla JS to set image src from data-attribute
问题描述
I'm looking for a way to set the src
of an image - in a modal - using the data attribute of a clickable element.
The markup for the element looks like this (there could be multiple of these on a page):
<span class="tooltip" data-imageToSet="someimage.jpg">Click me</span>
<div id="modal">
<img id="image" src="placeholder.jpg" />
</div>
<script>
var modal = document.getElementById('modal'),
modalImage = document.getElementById('image');
document.addEventListener('click', function(event) {
if (event.target.classList.contains('tooltip')) {
modal.classList.toggle('shown');
modalImage.src = event.currentTarget.dataset.imageToSet;
}
});
</script>
From what I've been reading up, this should work? But I keep getting a console error:
Uncaught TypeError: Cannot read property 'imageToSet' of undefined at HTMLDocument.<anonymous> ((index):1)
解决方案
你有两个问题。currentTarget 将是您将单击绑定到的元素,因此它将是文档。第二个问题是骆驼案例确实适用于数据集,您需要使用破折号。
var modal = document.getElementById('modal'),
modalImage = document.getElementById('image');
document.addEventListener('click', function(event) {
if (event.target.classList.contains('tooltip')) {
modal.classList.toggle('shown');
console.log(event.target)
modalImage.src = event.target.dataset.imageToSet;
}
})
<span class="tooltip" data-image-to-set="http://placekitten.com/300/300">Click me</span>
<div id="modal">
<img id="image" src="http://placekitten.com/g/200/300" />
</div>
推荐阅读
- r - 使用 R 对 RFC1738 进行 URL 解码(PHP 默认)
- python - Pyinstaller“无法执行脚本pyiboot01_bootstrap”
- android - 底部标签栏被推离屏幕底部,直到触摸事件
- reactjs - 使用 makeStyles - useStyles() 全局抛出 'Invalid Hook Call' 错误
- symfony4 - 如何使用角色过滤表单中的 EntityType?
- python - 防止 Cassandra Query 从缓存中受益
- fortran - Fortran 子例程:如何仅在第一次调用时加载数据
- php - 具有类别/专业的自定义组件和 router.php
- python - 使用 Selenium 接受 IE 网页对话框
- assembly - 如何使用汇编制作小型二进制文件?