2017-05-02 52 views
0

我試圖設置一個if/else語句,如果一個類存在,那麼var num將等於100,如果該類不存在,那麼var num將等於55. num然後是用於瞭解屏幕將被抵消多少像素。任何幫助將不勝感激,Javascript是我的薄弱點之一。If/Else jQuery is break my script

// Add scrollspy to <body> 
$('body').scrollspy({target: ".navbar", offset: 55}); 

// Checks to see if navbar is affixed or not 
if (($(".affix-top")[0]){) { 
    num = 100; 
} else { 
    num = 55; 
} 

// Add smooth scrolling on all links inside the navbar 
$(".navbar-lower a").on('click', function(event) { 

    // Make sure this.hash has a value before overriding default behavior 
    if (this.hash !== "") { 

    // Prevent default anchor click behavior 
    event.preventDefault(); 

    // Store hash 
    var hash = this.hash; 

    // Using jQuery's animate() method to add smooth page scroll 
    // The optional number (300) specifies the number of milliseconds it takes to scroll to the specified area 
    $('html, body').animate({ 
     scrollTop: $(hash).offset().top - num 
    }, 300, function(){ 

    // Add hash (#) to URL when done scrolling (default click behavior) 
     window.location.hash = hash; 
    }); 

    } // End if 

}); 
+7

您是否檢查過控制檯? ... if(($(「。affix-top」)[0]){){' – mhodges

+0

@mhodges當我粘貼到我的控制檯,它返回'未捕獲的SyntaxError:意外的令牌{' – Cody

+2

這就是他們'告訴你。你的代碼(他們完全複製)有一個語法錯誤 – Brennan

回答

0

這是難以閱讀。

if (($(".affix-top")[0]){) { 
    num = 100; 
} else { 
    num = 55; 
} 

它可以只是這個簡單,因爲任何匹配的是

var num = $(".affix-top").length ? 100 : 55; 

如果腳本在HTML頁面的其餘部分加載之前運行,那麼這將不起作用。

<script type="application/javascript"> $(".affix-top").length > 0; // false </script> 
<div class="affix-top"></div> 
<script type="application/javascript"> $(".affix-top").length > 0; // true </script> 

因此,把所有東西都包裝在一個jQuery ready塊中。

jQuery(document).ready(function(){ 
     var num = $(".affix-top").length ? 100 : 55; 
     //....... insert more code here 
    }); 
+0

我試過用這個,但是每次都打印出第二個數字,即使這個類不存在。 – Cody

+0

@Cike Affix有你可以聽的活動。這可能會提供更好的功能,然後匹配CSS類。讓一個讓:http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-affix.php – cgTag

0

你不需要額外的括號。此外,只需檢查.length以查看是否存在某個元素。這是主觀的,但海事組織使它更容易閱讀。

if ($(".affix-top").length) { 
    num = 100; 
} else { 
    num = 55; 
} 
0

你有一個{它不屬於

if (($(".affix-top")[0]){) { 

應該

if (($(".affix-top")[0])) {