簡體   English   中英

圖片上的可點擊標記(整個html集合上的一個事件偵聽器)-Javascript

[英]Clickable markers on image (one event listener on whole html collection) - Javascript

我在使標記在javascript中可點擊時遇到問題。 標記是圖片上的點,它們的html類是標記。 我希望它們全部都是可單擊的,然后測試單擊的標記是否具有我想要的ID(我可以對其進行測試)。

這是我正在談論的代碼:

function hladajEU(){
      var dlzkaPola = euRandomMesta.length;
      var klikanie = 0;
      var i=0;
      hladane = euRandomMesta.pop();
      var vsetkyMesta = document.getElementsByClassName("marker");
      console.log(vsetkyMesta);

         //document.getElementById('hladaneMesto').innerHTML= hladane.firstElementChild.nextElementSibling.childNodes[0].nodeValue;
          vsetkyMesta.onclick=function(){
              console.log("x");
          }   

  }

我希望整個標記列表都是可單擊的,但這不起作用。 有誰能夠幫助我? 我不想使用jQuery。 我想向HTML集合添加一個偵聽器。 當我不得不通過像vsektyMesta[i]這樣的集合時,如果可能的話,我想避免解決方案。

vsetkyMesta是HTML元素(標記)的數組。 您必須在循環塊中的每個標記上添加onclick處理程序。

您可以使用單擊事件使dom樹冒出氣泡這一事實,而不是為每個元素單獨創建一個偵聽器。 這意味着您可以在標記的父元素上設置一個事件,然后在偵聽器中檢查事件的目標是否為標記,如果是,則執行所需的操作。

因此,如果說下面是您的html標記:

<div class="container">
   <img src="http://placehold.it/350x350" />
   <div class="marker">1</div>
   <div class="marker">2</div>
   <div class="marker">3</div>
   <div class="marker">4</div>
</div>

然后,您需要做的就是在container上添加一個點擊監聽container然后檢查標記

document.querySelector(".container").addEventListener("click",function(e){
   //e.target will reference the element that triggered the event
   //classList.contains will return true if the element has a class
   //named marker
   if(e.target.classList.contains("marker")){
       console.log('x'); 
   }
});

Event.target參考

Element.classList參考

請注意,classList在大多數現代瀏覽器中都受支持,您將不得不使用其他方法來檢查那些沒有的類。

例如

e.target.className == "marker"

演示版

 var log = document.querySelector("#log"); document.querySelector(".container").addEventListener("click",function(e){ if(e.target.classList.contains("marker")){ log.innerText = "Clicked Marker: "+e.target.innerText; } }); Demo 
 .container { position:relative; } .marker { position:absolute; width:30px; height:30px; background:#D22; color:white; text-align:center; line-height:30px; z-index:10; } .marker:nth-child(1n){ top: 20px; left:35px; } .marker:nth-child(2n){ top: 50px; left:100px; } .marker:nth-child(3n){ top: 0px; right:0px; } .marker:nth-child(4n){ top: 100px; left:30px; } 
 <div class="container"> <img src="http://placehold.it/150x150" /> <div class="marker">1</div> <div class="marker">2</div> <div class="marker">3</div> <div class="marker">4</div> </div> <div id="log"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM