使用JavaScript没有库添加/删除类onclick

时间:2012-03-18 10:54:03

标签: javascript onclick addclass removeclass

我正在开发一个移动网站,并希望将JS用于添加和删除类。因此,为了保持良好和轻松,我不想使用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:

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 = '';
}

我不能让这个工作能让任何人告诉我我做错了什么?非常感谢提前。

根据以下提供的答案纠正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','');
}

2 个答案:

答案 0 :(得分:7)

您可以使用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','');
}

答案 1 :(得分:1)

它是.onclick,而不是.onClick