2

我正在开发一个移动站点,并且只想使用 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','');
}
4

2 回答 2

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','');
}
于 2012-03-18T10:56:18.283 回答
1

.onclick,不是.onClick

于 2012-03-18T11:05:24.287 回答