2017-07-18 44 views
-3

我在下面的JS中收到'navigateTo is not defined'錯誤。我很確定我已經通過了功能navigateTo作爲openCart()函數的一個參數,所以我不確定哪裏出錯了?將函數作爲參數傳遞到另一個函數錯誤

$(function() { 
    var form = $('form#checkout-form'), 
    $sections = $('[data-step]'); 

    function navigateTo(index) { 
     $sections.removeClass('is--active').eq(index).addClass('is--active'); 
    } 
}); 

$(document).on('click', 'nav.main a.cart', function(e) { 
    openCart(); 
}); 
function openCart(navigateTo) { 
    navigateTo(1); 
    disableScroll = false; 
} 
+2

的NavigateTo不在範圍之內。把這個功能放在更高的範圍內從其他功能調用 –

+3

這是非常簡單的事情。這一切都涉及到'範圍'。儘管你在'DOM'就緒函數中調用'openCart()','navigateTo()'沒有在'openCart()'的範圍內定義 – Ionut

回答

1

你的函數openCart應該去裏面的DOM準備功能,否則它不會調用函數,你需要回調作爲參數navigateTo傳遞到像openCart(navigateTo)opencart功能另一件事;

$(function() { 
 
    var form = $('form#checkout-form'), 
 
    $sections = $('[data-step]'); 
 

 
    function navigateTo(index) { 
 
    alert(2); 
 
     $sections.removeClass('is--active').eq(index).addClass('is--active'); 
 
    } 
 
    $(document).on('click', 'div', function(e) { 
 
     openCart(navigateTo); 
 
    }); 
 
    function openCart(navigateTo) { 
 
     navigateTo(1); 
 
     disableScroll = false; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div>hahah</div>

-1

這是一個範圍問題。把你的整個劇本封閉起來,你會好起來的;

(function($) { 
    // your script here 
})(jQuery) 

但是在第一個模塊周圍擺脫$(function() { }

相關問題