首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何让多个按钮调用同一个JavaScript

如何让多个按钮调用同一个JavaScript
EN

Stack Overflow用户
提问于 2014-07-03 08:02:20
回答 3查看 1.7K关注 0票数 0

我想知道为什么在这个问题上第一个按钮可以工作,而最后三个按钮不能。

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

如果我能得到任何关于我在哪里出错以及如何修复它的指点,那就太好了。

谢谢

JS:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
<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:

代码语言:javascript
运行
复制
#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;      
}
EN

Stack Overflow用户

发布于 2014-07-03 08:08:08

问题是您对每个标记使用相同的ID (每个按钮、div等都使用相同的id )。要解决此问题,您可以使用类而不是id,或者在HTML标记中使用事件触发器,并将名称添加到js函数中,如下所示:

html:

代码语言:javascript
运行
复制
<button onclick="popup1()"></button>

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

js:

代码语言:javascript
运行
复制
function popup1() {

//add whatever you need here

}

function popup2() {

//add whatever you need here

}
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24542962

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档