求事件委托的优雅写法

$('body').on('click',$("#id1"),function(){
     $('html body').animation({
        scrollTop: $("#id1").offset().top
    },0)
})
$('body').on('click',$("#id2"),function(){
     $('html body').animation({
        scrollTop: $("#id2").offset().top
    },0)
})

id选择器都是同一个button类型的,如果有多个button,优雅的写法应该怎么写
阅读 4.2k
8 个回答

你的代码看起来就很优雅。?

$('body').on('click',$(".className"),function(){
     $('html body').animation({
        scrollTop: $(this).offset().top
    },0)
})

//或者

$('body').on('click',$("#id1,#id2"),function(){
     $('html body').animation({
        scrollTop: $(this).offset().top
    },0)
})
$('body').on('click', 'button', function(){
     $('html body').animation({
        scrollTop: $(this).offset().top
    },0)
})

好多年没写过 jq 了,具体 api 忘了,大概就是这个意思

$(document).on('click', ev => {
  $('html, body').animation({ scrollTop: $(ev.target).offset().top })
})
function scrollToBtn(){
    var i = $(this).offset().top;
    $('body').scrollTop(i);
}
$(document).on('click', 'button', scrollToBtn);

另外歪个楼,如果没动画的话,应该也可以直接写锚点。

你既然同类型的按钮,那就给他们弄一个共性啊,直接点就是同样的class,干嘛要id

貌似这样?

$('body').on('click',function(e){
    var ev=e||window.event;
    var target=ev.target||ev.srcElement;
    var id=target.id;
    if(id.indexOf("id")!=-1){
        $('html body').animation({
            scrollTop: $(id).offset().top
        },0)
}
})
 
$(document).on('click', 'button', function(e){
    $('body').scrollTop($(this).offset().top);
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题