根据子字符串选择ID

时间:2020-04-17 02:17:15

标签: javascript

我的HTML中有一组图像,其ID为"Hole#" ex: "Hole1", "Hole2" ... "HoleN".。这些IMG标签正在加载本地存储的图像。我的目标是在单击其中一张图像时打印alert

我发现another个StackOverflow问题,我认为它将回答我的问题。我已将其合并到下面的代码中。不幸的是,它没有达到预期的效果。

//Dynamically creates images
for (let i = 1; i <= NUM_HOLES; i++) {
    let HoleID = `"hole${i}"`;
    let HoleIDPic = `"holePic${i}"`;
    holesString +=
    `<div id=`+ HoleID + `>
    <img id=` + HoleIDPic + ` src="" />
    </div>`
}

window.onload = function() {
      document.getElementById("img[id|=hole]").onclick = function()
      {
         alert("Clicked");
      };
   };

HTML:

   <section id="holes">

   </section>

将代码"img[id|=hole]"替换为"hole1"确实可以(对于Hole1),所以我得出了我的语法ID选择。

2 个答案:

答案 0 :(得分:1)

在所有图像上使用相似的id的整个想法是错误的方法。

请改用通用CSS类。然后,要找出单击了哪个图像,请使用单个委托侦听器,并使用自动传递给您的单击处理程序的事件对象。我正在向您展示一个使用按钮而不是图像的示例:

const buttonDiv = document.querySelector('.buttons');

// lets add some buttons
for (let i = 0; i < 5; i++) {
  let button = document.createElement('button');
  button.type = 'button';
  button.className = 'button';
  button.textContent = 'Button Number ' + i;
  buttonDiv.appendChild(button);
}

// now let's add a delegate click listener on the div containing the buttons
buttonDiv.addEventListener('click', function(event) {
  // in any event listener, the event object has a `target` property, telling you which element the event was raised on
  // this allows us to only react in the click listener if the clicked element meets certain conditions
  if (event.target.matches('button.button')) 
    console.log('you clicked on ' + event.target.textContent);
})
.buttons {
  background-color: #f0f0f0;
  padding: 10px;
}
<div class="buttons"></div>

答案 1 :(得分:0)

尝试一下

    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <section id="holes"></section>

    <script>    
      loadImages(2);
      
      function loadImages(NUM_HOLES){
        
        const sectionHoles = document.getElementById('holes');

        //Dynamically creates images
        for (let i = 1; i <= NUM_HOLES; i++) {

            let HoleID = `hole${i}`;
            let HoleIDPic = `holePic${i}`;

            let div = document.createElement('div');
            let img = document.createElement('img');

            div.id = HoleID;
            img.id = HoleIDPic;
            img.src = "someimage.png";

            // put image element in div
            div.appendChild(img);
            // put div in section
            sectionHoles.appendChild(div);

            // adding event listener to the img element
            document.getElementById(HoleIDPic).addEventListener('click', function(){
                alert(HoleIDPic + 'clicked');
            });
        }
   }
    </script>
</body>
</html>

相关问题