Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-创建一个函数并调用它_Javascript_Jquery - Fatal编程技术网

Javascript jQuery-创建一个函数并调用它

Javascript jQuery-创建一个函数并调用它,javascript,jquery,Javascript,Jquery,如何在jQuery中创建函数并调用它 这似乎不正确: var scrollLink = function() { $('html, body').animate({ scrollTop: $( $(this).attr('href') ).offset().top-20 }, 300); }; $('.js-ask').click(function(e) { e.preventDefault();

如何在jQuery中创建函数并调用它

这似乎不正确:

var scrollLink = function() {
        $('html, body').animate({
            scrollTop: $( $(this).attr('href') ).offset().top-20
        }, 300);
    };

    $('.js-ask').click(function(e) {
        e.preventDefault();
        $('[href="' + this.dataset.target + '"]').tab('show');
        reportReadMessages();
    });

    $(".js-scroll").click(function(e, scrollLink) {
        e.preventDefault();
        scrollLink();
    });

您没有在
scrollLink()
中传递此
的内容。它是一个参数为空的函数,当它不理解这是什么时。因此,请将其更改为:

$('.js-ask').click(function(e) {
    e.preventDefault();
    $('[href="' + this.dataset.target + '"]').tab('show');
    reportReadMessages();
});

$(".js-scroll").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top-20
    }, 300);
});
您没有以正确的方式传递
滚动链接。这就是它不起作用的原因

也可以通过以下方式扩展该功能:

$.fn.scrollLink = function() {
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top-20
    }, 300);
};
您可以调用以下元素:

$(this).scrollLink();
$(selector).scrollLink();

有关更多信息,请参阅。

您没有在
滚动链接()中传递
这个
的内容。它是一个参数为空的函数,当它不理解这是什么时。因此,请将其更改为:

$('.js-ask').click(function(e) {
    e.preventDefault();
    $('[href="' + this.dataset.target + '"]').tab('show');
    reportReadMessages();
});

$(".js-scroll").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top-20
    }, 300);
});
您没有以正确的方式传递
滚动链接。这就是它不起作用的原因

也可以通过以下方式扩展该功能:

$.fn.scrollLink = function() {
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top-20
    }, 300);
};
您可以调用以下元素:

$(this).scrollLink();
$(selector).scrollLink();

有关更多信息,请参阅。

Nice!非常感谢。是的,对不起,我只是从jQuery开始。但你的解决方案让我明白了很多事情。谢谢,很好!非常感谢。是的,对不起,我只是从jQuery开始。但你的解决方案让我明白了很多事情。谢谢