Add/Remove class onclick with JavaScript no librarys

China☆狼群 提交于 2019-12-12 19:14:16

问题


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.

I have the following 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:

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:

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','');
}

回答1:


You can use 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','');
}



回答2:


It's .onclick, not .onClick



来源:https://stackoverflow.com/questions/9757717/add-remove-class-onclick-with-javascript-no-librarys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!