2015-01-15 26 views
0

我想知道javascript中的classname與jQuery中的addClass是否相同。 我想改變下列函數的jQuery:Classname javascript與addClass jQuery相同?

function slidePageFrom(page, from) { 
     // Position the page at the starting position of the animation 
     page.className = "page " + from; 
     // Position the new page and the current page at the ending position of their animation with a transition class indicating the duration of the animation 
     page.className ="page transition center"; 
     currentPage.className = "page transition " + (from === "left" ? "right" : "left"); 
     currentPage = page; 
    } 

HTML:

<section id="homePage" class="page center" style="background-color: #add55a"> 
     <h1>Home Page</h1> 
     <a href="javascript:slidePageFrom(page1, 'right');">Page 1</a> 
    </section> 

    <section id="p1" class="page right" style="background-color: #8ca83d"> 
     <h1>Page 1</h1> 
     <a href="javascript:slidePageFrom(page2, 'right');">Back</a> 
    </section> 
    <section id="p2" class="page right" style="background-color: #8ca83d"> 
     <h1>Page 2</h1> 
     <a href="javascript:slidePageFrom(homePage, 'left');">Back</a> 
    </section> 
+0

該函數中的第二條語句完全不符合第一條語句的作用。 – Pointy

+0

jquery addClass將保留舊類並添加新類,您還可以使用removeClass刪除類 – brso05

+0

@Pointy這就是它的意思;它是一個動畫(使用CSS轉換) – Tyblitz

回答

2

DOM元素節點的className屬性的所有該節點上的班空格分隔的列表。如果元素具有類「a」,「b」和「c」,則.className將爲"a b c"(可能以其他順序,因爲順序無關緊要)。

相比之下,jQuery .addClass().removeClass()函數按照他們的說法:添加一個類(如果它不在那裏)或刪除一個類(如果它是)。這些行動隻影響涉及的類別;其他人留在原地。

所以答案是jQuery方法爲您提供了一個抽象來操縱.className屬性,但是說它們是「相同的」屬性是不正確的。

注意,在你的函數,這些前兩個語句:

page.className = "page " + from; 
    // Position the new page and the current page at the ending position of their animation with a transition class indicating the duration of the animation 
    page.className ="page transition center"; 

第二分配到.className財產完全覆蓋由第一個語句放在那裏的價值。換句話說,無論from的值是多少,page.className的值在第二個語句後將會是總是"page transition center"。如果,另一方面,第二條語句曾使用jQuery的.addClass()

$(page).addClass("page transition center"); 

然後後,無論類名是from將仍然存在。