添加/删除类onclick与JavaScript没有图书馆

我正在开发一个移动网站,并希望使用JS只是添加和删除类。 因此,为了保持良好和轻松,我不想使用jQuery。

我有以下HTML:

 

以及到目前为止的以下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',''); } 

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

它是.onclick ,而不是.onClick