2017-07-26 165 views
0

我是JavaScript新手,所以原谅我,如果我的问题听起来很愚蠢。 我有不同的图标(相同的图标一再重复)代表我的网页上通过为同一HTML页面上的不同按钮调用相同的onClick函数

<img src="/images/info_icon.gif" id="tooltip_icon" alt="hee haa"> 
<img src="/images/info_icon.gif" id="tooltip_icon" alt="hee haa"> 
<img src="/images/info_icon.gif" id="tooltip_icon" alt="hee haa"> 

现在,我想打电话给打开弹出式窗口中的JavaScript功能,当我点击这些图标 -

// Get the modal 
var modal = document.getElementById('myModal'); 

// Get the button that opens the modal 
var btn = document.getElementById("tooltip_icon"); 

// Get the <span> element that closes the modal 
var span = document.getElementsByClassName("close")[0]; 

// When the user clicks the button, open the modal 
btn.onclick = function() { 
    modal.style.display = "block"; 
} 

// When the user clicks on <span> (x), close the modal 
span.onclick = function() { 
    modal.style.display = "none"; 
} 

// When the user clicks anywhere outside of the modal, close it 
window.onclick = function(event) { 
    if (event.target == modal) { 
     modal.style.display = "none"; 
    } 
} 

现在,因为我试图通过ID获取元素,只有其中一个图标导致模态被点击时,该功能未被调用(显然),当我点击其他人。

我想要相同的功能被称为,如果我点击任何图标。

我该如何做到这一点?请在这里找到我的代码 - https://jsfiddle.net/up5bd22s/1/

在此先感谢!

回答

0

不能对不同的元素使用多个相同id秒 - 这是无效的HTML。 id意思是独特 - 很像社会保险号码是一种独特的身份证。

我想你想获得元素的集合,然后遍历它们来更新它们的onclick。我建议重构像这样

// Get the modal 
var modal = document.getElementById('myModal'); 

// Get the button that opens the modal 
var btn = document.getElementsByClassName(".tooltip_icon"); 

// Get the <span> element that closes the modal 
var span = document.getElementsByClassName("close")[0]; 

// When the user clicks the button, open the modal 
function displayModal() { 
    modal.style.display = "block"; 
} 

// When the user clicks on <span> (x), close the modal 
function hideModal() { 
    modal.style.display = "none"; 
} 

for (var i=0; i<btn.length; i++) { 
    btn[i].onclick = displayModal; 
} 

span.onclick = hideModal; 

// When the user clicks anywhere outside of the modal, close it 
window.onclick = function(event) { 
    if (event.target == modal) { 
     hideModal(); 
    } 
} 

(这是当然的,更新的反复id s转换课后。)

3

您可以使用class属性而不是id,并将事件侦听器添加到所有匹配class的元素,如下所示。

https://jsfiddle.net/up5bd22s/2/

function showPopup(){ 
modal.style.display = "block"; 
} 

var btns = document.getElementsByClassName("tooltip_icon"); 


for (var i = 0; i < btns.length; i++) { 
    btns[i].addEventListener('click', showPopup, false); 
} 
相关问题