2012-03-18 77 views
2

我正在开发一个移动网站,并希望只使用JS而不仅仅是添加和删除类。所以,为了保持好的东西,我不想使用jQuery。使用JavaScript添加/删除类onclick没有图书馆

我有以下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',''); 
} 
+0

我认为这个问题已经回答这里http://stackoverflow.com/questions/5169017/how-to-remove-class-attribute-from-div – 2012-03-18 10:59:00

回答

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

喜并感谢您的回答我已经修改了我的脚本以使用您的建议,但在Chrome Dev Tools中检查我的代码时看不到它的正常工作。 – mtwallet 2012-03-18 10:59:59

+0

我也改变了'openPrimaryNav()''openPrimaryNav'和'closePrimaryNav()'到'closePrimaryNav'。 – Engineer 2012-03-18 11:00:52

+0

对我也是我直接复制你的代码 – mtwallet 2012-03-18 11:02:52