我想知道为什么在这个问题上第一个按钮可以工作,而最后三个按钮不能。
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;
}发布于 2014-07-03 08:10:38
id属性必须是唯一的,因此每个id不能超过一个。我建议在使用getElementsByClassName而不是getElementsById时使用class属性。
发布于 2014-07-03 08:08:08
问题是您对每个标记使用相同的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
}发布于 2014-07-03 08:12:16
您不能为您的按钮(或任何其他元素)提供相同的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
https://stackoverflow.com/questions/24542962
复制相似问题