首页 > 解决方案 > 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)

标签: javascriptcustom-data-attribute

解决方案


你有两个问题。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>


推荐阅读