2012-03-18 80 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