2017-04-14 5 views
2

JavaScriptを私はJavaScriptのモジュールのパターンを使用してボタンをクリックし、「スムーズスクロール」を結合するためのスクリプトを書きました。私はモジュールのパターンにコードを書き、初めてなのでは、このモジュールのパターン

は、私が「これ」の使用に関するいくつかの助けを必要としています。

私は私の「bindevents」機能に関数を「スクロール」バインドするとき、私は「これ」というエラーを取得し、「スクロール」機能では、未定義です。

は、どのように私は「これは」私はクリックボタンを選択するために使用する必要がありますか?

var s, SmoothScroll = { 
 

 
    Selectors: { 
 
    Link: $('a[href*="#"]:not([href="#"])') 
 
    }, 
 

 
    scroll: function() { 
 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname && $(".classes .section").has(this).length == 0) { 
 
     var target = $(this.hash); 
 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
 
     if (target.length) { 
 
     $('html, body').animate({ 
 
      scrollTop: target.offset().top 
 
     }, 1000); 
 
     return false; 
 
     } 
 
    } 
 
    }, 
 

 
    bindEvents: function() { 
 
    s.Link.click(function() { 
 
     SmoothScroll.scroll(); 
 
    }); 
 
    }, 
 

 
    init: function(){ 
 
    s = this.Selectors; 
 
    this.bindEvents(); 
 
    } 
 

 
}; 
 

 
SmoothScroll.init();

答えて

2

変更:今すぐ

s.Link.click(SmoothScroll.scroll); 

0に

s.Link.click(function() { 
    SmoothScroll.scroll(); 
}); 

ここ

コードですscroll関数内はthisの異なるコンテキストが混乱している場合、あなたはscroll代わり

bindEvents: function() { 
    s.Link.click(function() { 
    // "this" is element determined by jQuery 
    SmoothScroll.scroll(this); 
    }); 
}, 
scroll: function(link) { 
    // this === SmoothScroll 
    if (location.pathname.replace(/^\//,'') == link.pathname.replace(/^\//,'') && location.hostname == link.hostname && $(".classes .section").has(link).length == 0) { 
     var target = $(link.hash); 
    ..... 
+0

おかげでたくさんの引数として要素を渡すことができる要素


になります!今それは動作します。この場合には、私は()せずにスクロールを使用する理由私はちょうど..疑問を持っていますが、init関数内で私がbindeventsを使用する()()と? – Matteo

+1

要素のコンテキストとして 'this'を取得する匿名関数を渡すのではなく、参照として関数を渡しているからです。 – charlietfl

+0

そしてbindEventsの中でもっと多くの関数をバインドする必要がある場合はどうしたらいいですか? – Matteo

関連する問題