使用JavaScript没有库添加/删除类onclick [英] Add/Remove class onclick with JavaScript no librarys
本文介绍了使用JavaScript没有库添加/删除类onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个移动网站,除了添加和删除类外,我只想使用JS.因此,为了保持美观和轻巧,我不想使用jQuery.
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.
我有以下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>
以及到目前为止的以下JS:
and the following JS so far:
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.
基于下面提供的答案的正确JS:
CORRECT JS BASED ON ANSWER PROVIDED BELOW:
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','');
}
推荐答案
您可以使用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','');
}
这篇关于使用JavaScript没有库添加/删除类onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文