【问题标题】:Is there a way to consolidate jQuery functions which do the same thing but on different classes and ids有没有办法整合 jQuery 函数,这些函数做同样的事情,但在不同的类和 id 上
【发布时间】:2017-12-03 00:59:18
【问题描述】:

我的代码如下:

 $('.contact_btn').click(function(){
    $('.modal').modal('hide');
     $('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 1000);

});

$('.insurance_btn').click(function(){
    $('.modal').modal('hide');
     $('html, body').animate({
        scrollTop: $("#insuranceFormTop").offset().top
    }, 1000);

});

$('.bmw_btn').click(function(){
    $('.modal').modal('hide');
     $('html, body').animate({
        scrollTop: $("#bmwContactTop").offset().top
    }, 1000);

});

有没有办法只制作一个函数,该函数接受类并作用于各自的 id。

【问题讨论】:

  • 只需创建一个接受类和 id 的函数,并用各自的对调用它三次。
  • @Berji 基本上这是我想要做的,但我对 jQuery 很陌生,在实现这一点时遇到了很多麻烦。
  • 这与jQuery无关。它只是一个执行 javascript 代码(使用 jQuery 库)的 javascript 函数。
  • @Bergi 可耻,我不知道如何实现这一目标。
  • 取重复的代码,把它放在function name(){ … }中,然后为每次重复中不同的那些小东西添加参数,并使用这些变量而不是值。然后调用那个函数。

标签: javascript jquery jquery-events


【解决方案1】:

你可以这样做

$('.contact_btn').click(function(){
    animate('contact');
});

function animate(id) {
    $('.modal').modal('hide');
    $('html, body').animate({
        scrollTop: $("#"+id).offset().top
    }, 1000);
}

它会为你工作。

【讨论】:

  • 如果我这样做,仍然意味着我必须编写三遍代码。我不想这样做。我需要一个接受 divs 类并对其进行操作的代码。例如。
【解决方案2】:
  function simplefunction(classname,id){
    $('.'+classname).click(function(){
        $('.modal').modal('hide');
         $('html, body').animate({
            scrollTop: $("#"+id).offset().top
        }, 1000);

    });
    }


<div class="relevant_button" id="respective_I‌D" onclick="simplefunction(this.getAttribute('class'),this.id)"> 

【讨论】:

  • 那是我试过的。如果有帮助,请检查我在下面的答案中留下的评论。非常感谢您在这方面的帮助,我可以看到这个答案非常接近我想要实现的目标。
  • 哈哈,看起来很有趣。你能编辑它,让它使用 dosomething 函数吗?
  • 这真的很有帮助,非常感谢您的帮助
  • padhwal 我尝试使用此功能但它不起作用。在尝试功能之前我忘记保存 js 文件,我测试的是我之前的原始功能。我在 onclick 上附加了另一个函数,控制台在 scroll_to_the_top_of_the_respective_id_and_close_th‌​e_modal 函数上抛出了一个未定义的错误
  • 把函数名从这么繁琐的改成简单的,看看编辑后的代码,把id和类一起传递。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2020-07-31
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多