Добавить / удалить класс onclick с JavaScript без библиотек - PullRequest
2 голосов
/ 18 марта 2012

Я занимаюсь разработкой мобильного сайта и хочу использовать 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 ]

7 голосов
/ 18 марта 2012

Вы можете использовать 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 голос
/ 18 марта 2012

Это .onclick, а не .onClick

...