javascript anchor avoid scroll to top on click

前端 未结 5 1658
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 14:47

I created a function in javascript that i add to an anchor as such

javascript :

somefunction = function () {alert(\'foo\')}

html :

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 15:11

    The trick is that your onclick returns the value of somefunction, so that if you make sure somefunction always return false, then the event will return false as well, and cancel the default behavior of the anchor.

    So this should solve your problem:

    somefunction = function () { alert('foo'); return false; }
    

    But I should mention that when there is an error somewhere in somefunction, the rest of the javascript will not execute, and the browser will still follow the link to #. It is advisable, therefore, to use javascript:void(0) instead, as this will rid you of that problem.

提交回复
热议问题