【发布时间】:2013-07-31 02:24:40
【问题描述】:
我正在尝试创建对 click 方法的回调函数的引用。我希望this 引用被点击的href。我该怎么做呢?我已经阅读了有关使用 .call 方法的信息,但对我来说并不是 100% 清楚..
下面是我正在处理的代码 sn-p。我在遇到问题的地方留下了评论。
var scrollTo = {
init: function(config) {
var href = config.element;
href.on('click', this.scroll);
},
scroll: function(e) {
var target = this.attr('href'), // I would like "this" to refer to the href.onClick element
sT = $(target).offset().top;
console.log(this);
$('html, body').animate({
scrollTop: sT
}, 2000);
e.preventDefault();
}
}
scrollTo.init({
element: $('a[href^="#"]')
});
【问题讨论】:
-
this指向触发事件的元素....您希望它指向哪个对象 -
我想让
this指向被点击的href元素(可以在init函数中找到) -
它指向那个元素
-
对!我的错。我只需要写
$(this).attr而不是this.attr。感谢您的帮助,4 分钟后我可以点击绿色复选标记 :)
标签: javascript jquery call