防止在内部 JavaScript 函数中滚动到顶部的任何方法

Any way to prevent scrolling to top in the inner javascript function?

本文关键字:顶部 任何 方法 滚动 在内部 JavaScript 函数      更新时间:2023-09-26
什么是

javascript/jQuery解决方案,以防止在单击内部javascript函数inner()的链接时滚动到顶部?

解决方案应该在内部函数中。是否可以不将事件作为参数传递? 下面的代码中提供了其他解决方案并附有解释,但是没有人在inner()中用作解决方案。代码如下。请滚动到最下面的链接。inner()函数中的最低链路需要该解决方案。

这是jsFiddle代码:

.html:

<div>
    <p><a href="#">it jumps</a></p>
    <p><a href="#">it jumps</a></p>
    <p><a href="#">it jumps</a></p>
    <p><a href="#">it jumps</a></p>
    <p><a href="javascript:void(0);" id="jsSolution">no jumps - jsSolution</a></p>
    <p><a href="#" id="jqSolution">no jumps - jqSolution</a></p>
    <p><a href="#!">no jumps - html Solution</a></p>
    <p><a href="#" id="problem">how to prevent this from jumping - javascript solution in the add() function</a></p>
</div>

JavaScript:

$(function(){
    function inner(){

        //prevent from scrolling to top here - solution is needed here;
        return 4;
    }
    function add() {
        alert('how to prevent jumping to top in the add function');
        var counter = 0;
        var res=inner();
        alert(res);//4
        //some code goes here
        //and here
        //this doesn't work e.preventDefault();
        return counter; 
    }
    $('#jqSolution').click(function(e) {
     //return false; 
     e.preventDefault(); // same thing as above
    });
    $('#problem').click(function(e) {
         add();
    });
});

包括jQuery库。

.css:

div{
border:1px solid red;
    width:200px;
}
p{
    padding:50px;
}

谢谢。

附言链接 href="#" 不能更改,javascript 代码不应该被销毁。

我不认为我完全得到了你,但你可以使用 preventDefault 这样就不会执行锚标签的默认操作。Js 对您的小提琴进行了一些更改以使其工作:-

http://jsfiddle.net/sahilbatla/guxdku9w/2/

$(function(){
    function inner(e){
        e.preventDefault();
        //prevent from scrolling to top here - solution is needed here;
        return 4;
    }
    function add(e) {
        alert('how to prevent jumping to top in the add function');
        var counter = 0;
        var res=inner(e);
        alert(res);//4
        return counter; 
    }
    $('#jqSolution').click(function(e) {
     //return false; // prevent default click action from happening
     e.preventDefault(); // same thing as above
    });
    $('#problem').click(function(e) {
         add(e);
    });
});