我正在開發一個移動網站,並希望只使用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','');
}
我認爲這個問題已經回答這裏http://stackoverflow.com/questions/5169017/how-to-remove-class-attribute-from-div – 2012-03-18 10:59:00