Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这是基于JavaScript模块模式的_Javascript_Jquery_Module - Fatal编程技术网

这是基于JavaScript模块模式的

这是基于JavaScript模块模式的,javascript,jquery,module,Javascript,Jquery,Module,我编写了一个脚本,用于使用JavaScript模块模式单击按钮绑定“平滑滚动” 因为这是我第一次在模块模式上编写代码,所以我需要一些关于“this”使用的帮助 当我将“scroll”函数绑定到我的“bindevents”函数时,我得到一个错误,表示“scroll”函数中的“this”未定义 我应该如何使用“this”来选择我单击的按钮 代码如下: var s,平滑滚动={ 选择器:{ 链接:$('a[href*=“#”]:不是([href=“#”])) }, 滚动:函数(){ 如果(locat

我编写了一个脚本,用于使用JavaScript模块模式单击按钮绑定“平滑滚动”

因为这是我第一次在模块模式上编写代码,所以我需要一些关于“this”使用的帮助

当我将“scroll”函数绑定到我的“bindevents”函数时,我得到一个错误,表示“scroll”函数中的“this”未定义

我应该如何使用“this”来选择我单击的按钮

代码如下:

var s,平滑滚动={
选择器:{
链接:$('a[href*=“#”]:不是([href=“#”]))
},
滚动:函数(){
如果(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(目标长度){
$('html,body')。设置动画({
scrollTop:target.offset().top
}, 1000);
返回false;
}
}
},
bindEvents:函数(){
s、 Link.click(函数(){
scroll();
});
},
init:function(){
s=这个。选择器;
这是bindEvents();
}
};
SmoothScroll.init()更改:

s.Link.click(function() {
  SmoothScroll.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);
  .....  

谢谢!!现在它起作用了。我只是有个问题。。为什么在这种情况下我不使用scroll(),但在init函数中我使用bindevents()和()?因为您将函数作为引用传递,而不是传递一个匿名函数,该匿名函数将获得
this
作为元素的上下文,如果我需要在bindevents中绑定更多函数,该怎么办?这取决于您需要做什么。如果它们是事件侦听器,则会执行与click@Matteo那你应该用!或者将元素作为参数传递!
 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);
  .....