如何让多个按钮调用相同的JavaScript

时间:2014-07-03 00:02:20

标签: javascript html arrays button multiple-instances

我想知道为什么第一个按钮有效,最后三个按钮没有解决我遇到的这个问题。

http://jsfiddle.net/j4c7U/387/

如果我能找到我出错的地方以及如何解决它,那将会很棒。

由于

JS:

window.onload = function() {
  document.getElementById("LearnMoreBtn").onclick = function(){
        var overlay = document.getElementById("overlay");
        var popup = document.getElementById("popup");
        overlay.style.display = "block";
        popup.style.display = "block";
};

  document.getElementById("CloseBtn").onclick = function(){
        var overlay = document.getElementById("overlay");
        var popup = document.getElementById("popup");
        overlay.style.display = "none";
        popup.style.display = "none";      
  }
};

HTML:

<button id="LearnMoreBtn">Learn More</button>
<div id="overlay"></div>
<div id="popup">
    Popup contents here
    <button id="CloseBtn">ClosePopup</button>
</div>
<div>
some other content that will be behind the popup
</div><button id="LearnMoreBtn">Learn More</button>
<div id="overlay"></div>
<div id="popup">
    Popup contents here
     <button id="CloseBtn">ClosePopup</button>
</div>
<div>
    some other content that will be behind the popup
</div><button id="LearnMoreBtn">Learn More</button>
<div id="overlay"></div>
<div id="popup">
    Popup contents here
    <button id="CloseBtn">ClosePopup</button>
</div>
<div>
some other content that will be behind the popup
</div><button id="LearnMoreBtn">Learn More</button>
<div id="overlay"></div>
<div id="popup">
Popup contents here
<button id="CloseBtn">ClosePopup</button>
</div>
<div>
some other content that will be behind the popup
</div>

CSS:

#overlay {
display:none;    
position:fixed;  
left:0px;        
top:0px;         
width:100%;      
height:100%;     
background:#000; 
opacity:0.5;     
z-index:99999;   
}

#popup {
display:none;
position:fixed;
left:50%;        
top:50%;         
width:300px;     
height:150px;
margin-top:-75px;
margin-left:-150px;
background:#FFFFFF;
border:2px solid #000;
z-index:100000;      
}

3 个答案:

答案 0 :(得分:3)

id属性必须是唯一的,因此您不能拥有多个ID。我建议使用class属性而不是getElementsByClassName代替getElementsById

答案 1 :(得分:1)

问题是你为每个标签使用相同的ID(每个按钮,div等都使用相同的ID)来解决这个问题,你可以使用类而不是ID,或者在HTML标签中添加事件触发器并添加名称到js函数,像这样:

HTML:

<button onclick="popup1()"></button>

<button onclick="popup2()"></button>

JS:

function popup1() {

//add whatever you need here

}

function popup2() {

//add whatever you need here

}

答案 2 :(得分:0)

您无法为您的按钮(或任何其他元素)提供相同的ID 您可以为它们提供唯一ID并单独定位它们,也可以使用querySelectorAll或getElementsByClassName。这些方法将返回一个可以循环的节点列表并分配点击事件。

https://developer.mozilla.org/en/docs/Web/API/Document.querySelectorAll

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName