简体   繁体   中英

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

I have a simple nav menu with submenus. When the links in the submenu are clicked while on the same page, the window scrolls using jQuery to the respective anchor.

Here is an example of a submenu list item:

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

The corresponding anchor looks like this:

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

The JavaScript function:

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

It all works perfectly fine, but like many before me I have been reading that inline event handlers are bad practice these days.

How can I modify the function to eliminate the need for any onclick calls? Keep in mind that each submenu link corresponds to a different anchor.

Assuming that you want all anchors with a hash # to scroll to a corresponding anchor with the same ID, you can loop through all anchors, parse out the hash and scroll to the same 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/

If you want to limit this functionality to certain anchors, add a class and insert it in the selector, f.ex $('a.hashlink').each(

Use event handlers: 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);; }());

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM