在这种情况下使用onclick事件处理程序可以接受吗

Is it acceptable to use the onclick event handler in this case?

本文关键字:程序 事件处理 这种情况下 onclick      更新时间:2023-09-26

我有一个带子菜单的简单导航菜单。当在同一页面上单击子菜单中的链接时,窗口会使用jQuery滚动到相应的锚点。

以下是子菜单列表项的示例:

<li><a href="page.html#some-anchor" onclick="clickScroll('#some-anchor');"><span>foo</span></a></li>

相应的锚点如下所示:

<a class="hidden-anchor" id="some-anchor" name="some-anchor"></a>

JavaScript函数:

function clickScroll(dest) {
    $('html, body').stop().animate({
        scrollTop: $(dest).offset().top
    }, 1000);
}

这一切都很好,但和我之前的许多人一样,我一直在读到内联事件处理程序这些天是不好的做法。

如何修改函数以消除对任何onclick调用的需要?请记住,每个子菜单链接都对应于不同的锚点。

假设您希望具有哈希#的所有锚都滚动到具有相同ID的相应锚,则可以循环浏览所有锚,解析出哈希并滚动到相同ID:

$('a').each(function() {
    if ( this.hash ) {
        $(this).click(function(e) {
            $('html,body').animate({ scrollTop: $(this.hash).offset().top }, 1000);
            e.preventDefault();
        });
     }
});

http://jsfiddle.net/nGfW5/

如果您想将此功能限制为某些锚点,请添加一个类并将其插入选择器中,例如$('a.hashlink').each(

使用事件处理程序:http://api.jquery.com/on/

<li><a id="some-scroll-source" href="page.html#some-anchor"><span>foo</span></a></li>
<a class="hidden-anchor" id="some-anchor" name="some-anchor"></a>
(function () {
    function clickScroll() {
        var dest = $('#' + ($(this).attr('href').split('#')[1]));
        $('html, body').stop().animate({
            scrollTop: $(dest).offset().top
        }, 1000);
    }
    $('#some-scroll-source').on('click', clickScroll);;
}());

试试这个:

$('li a').each (function () {
    $(this).click(function () {
        $('html, body').stop().animate({
           scrollTop: $(this.hash).offset().top
        }, 1000);
    });
});