使用普通JS从数据属性设置图像src

问题描述 投票:0回答:2

[我正在寻找一种使用可点击元素的data属性以模态设置图像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)
javascript custom-data-attribute
2个回答
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>

0
投票

首先检查target(即被单击的元素)是否具有工具提示类

event.target.classList.contains('tooltip')

但是然后您使用currentTarget(即事件处理程序绑定到的元素:document)来读取数据集。

modalImage.src = event.currentTarget.dataset.imageToSet

您需要继续使用target

© www.soinside.com 2019 - 2024. All rights reserved.