添加/删除类 onclick 与 JavaScript 无库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9757717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add/Remove class onclick with JavaScript no librarys
提问by mtwallet
I am developing a mobile site and want to use JS for nothing more than adding and removing classes. So, in the interest of keeping things nice and light I don't want to use jQuery.
我正在开发一个移动站点,并且只想使用 JS 来添加和删除类。所以,为了让事情变得简单明了,我不想使用 jQuery。
I have the following HTML:
我有以下 HTML:
<div id="masthead">
<a href="index.html" title="Home" id="brand">Brand</a>
<a href="#" id="openPrimaryNav">Menu</a>
<ul id="primaryNav" class="">
<li><a href="index.html" title="Home">Home</a></li>
<li><a href="benefits.html" title="Benefits">Benefits</a></li>
<li><a href="features.html" title="Features">Features</a></li>
<li><a href="casestudies.html" title="Case Studies">Case Studies</a></li>
<li><a href="instore.html" title="In Store">In-Store</a></li>
<li><a href="contact.html" title="Contact">Contact Us</a></li>
<li id="closePrimaryNav"><a href="#" title="Contact">Close Menu</a></li>
</ul>
</div>
and the following JS so far:
和以下 JS 到目前为止:
window.onLoad = init;
function init()
{
document.getElementById('openPrimaryNav').onClick = openPrimaryNav();
document.getElementById('closePrimaryNav').onClick = closePrimaryNav();
}
function openPrimaryNav()
{
document.getElementById('primaryNav').className = 'open';
}
function closePrimaryNav()
{
document.getElementById('primaryNav').className = '';
}
I cannot get this working can anyone tell me what I am doing wrong? Many thanks in advance.
我无法完成这项工作,谁能告诉我我做错了什么?提前谢谢了。
CORRECT JS BASED ON ANSWER PROVIDED BELOW:
基于以下提供的答案正确的 JS:
window.onload = init;
function init()
{
document.getElementById('openPrimaryNav').onclick = openPrimaryNav;
document.getElementById('closePrimaryNav').onclick = closePrimaryNav;
}
function openPrimaryNav()
{
document.getElementById('primaryNav').setAttribute('class','open');
}
function closePrimaryNav()
{
document.getElementById('primaryNav').setAttribute('class','');
}
回答by Engineer
You can use setAttribute
.
您可以使用setAttribute
.
window.onload = init;
function init()
{
document.getElementById('openPrimaryNav').onclick = openPrimaryNav;
document.getElementById('closePrimaryNav').onclick = closePrimaryNav;
}
function openPrimaryNav()
{
document.getElementById('primaryNav').setAttribute('class','open');
}
function closePrimaryNav()
{
document.getElementById('primaryNav').setAttribute('class','');
}
回答by Alnitak
It's .onclick
, not .onClick
是.onclick
,不是.onClick