我正在寻找一种方法,使用可点击元素的数据属性以模态设置图像的src
。
元素的标记如下(一个页面上可能有多个这样的标记(:
<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>
根据我所读到的,这应该有效吗?但我不断收到控制台错误:
Uncaught TypeError: Cannot read property 'imageToSet' of undefined at HTMLDocument.<anonymous> ((index):1)
您有两个问题。currentTarget将是您将单击绑定到的元素,因此它将是文档。第二个问题是camel-case确实适用于数据集,您需要使用破折号。
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>
首先检查target
(即单击的元素(是否具有工具提示类
event.target.classList.contains('tooltip')
但是您使用currentTarget
(即事件处理程序绑定到的元素:document
(来读取数据集。
modalImage.src = event.currentTarget.dataset.imageToSet
您需要在整个过程中继续使用target
。