jQuery在函数中阻止了默认

Ala*_*tis 5 javascript jquery

我用过preventDefault像这样的元素事件:

$('#element').click(function (e) {
    do stuff...
});
Run Code Online (Sandbox Code Playgroud)

现在,我有一个函数,它已经在我想要使用的参数,preventDefault但我不知道如何:

<a href="#services" id="services_link" class="services" onclick="sectionScroll('services')">Services</a>


function sectionScroll(id) {
    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用return false,但是当点击链接时,这会导致一些闪烁.

如何添加preventDefault上述功能?

编辑

我最初的问题是在具有其他参数的函数中使用preventDefault.我最后不需要使用内联javascript(它看起来似乎没有办法避免它),所以这就是我使用的.我觉得它很整洁:

<a href="#services" class="menu-link">Services</a>


   $('.menu-link').click(function (e) {
        e.preventDefault();
        var location = $(this).attr('href');
        history.pushState(null, null, location)
        $('html, body').animate({
            scrollTop: $(location).offset().top
        }, 1000);
    });
Run Code Online (Sandbox Code Playgroud)

Kor*_*lum 10

好吧,如果你真的想使用内联事件处理程序(虽然不推荐它),试试这个:

<a href="#services" id="services_link" class="services"
   onclick="sectionScroll('services', event)">Services</a>

<script type="text/javascript">
function sectionScroll(id, e) {
    e.preventDefault();
    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);
}
</script>
Run Code Online (Sandbox Code Playgroud)