Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.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 有没有更有效的方法?_Javascript_Jquery_Performance_Optimization - Fatal编程技术网

Javascript 有没有更有效的方法?

Javascript 有没有更有效的方法?,javascript,jquery,performance,optimization,Javascript,Jquery,Performance,Optimization,如何更轻松地实现此代码或使用更少的代码行? 我很好奇是否可以更容易和/或更有效地完成。因为我觉得这里面有太多的重复,所以必须有一个简单的方法。 我不仅计划做4个,而且要做20-30个,所以性能是一个关键方面 Jquery: $( document ).ready(function() { $( "#q1" ).click(function() { $( "#a1" ).slideToggle( "slow&

如何更轻松地实现此代码或使用更少的代码行? 我很好奇是否可以更容易和/或更有效地完成。因为我觉得这里面有太多的重复,所以必须有一个简单的方法。 我不仅计划做4个,而且要做20-30个,所以性能是一个关键方面

Jquery:

$( document ).ready(function() {
        $( "#q1" ).click(function() {
            $( "#a1" ).slideToggle( "slow", function() {});
            if ($(this).hasClass('on')){
                    $(this).removeClass('on');
            }else{
                $(this).addClass('on');
            }
        });
        $( "#q2" ).click(function() {
            $( "#a2" ).slideToggle( "slow", function() {});
            if ($(this).hasClass('on')){
                    $(this).removeClass('on');
            }else{
                $(this).addClass('on');
            }
        });
        $( "#q3" ).click(function() {
            $( "#a3" ).slideToggle( "slow", function() {});
            if ($(this).hasClass('on')){
                    $(this).removeClass('on');
            }else{
                $(this).addClass('on');
            }
        });
        $( "#q4" ).click(function() {
            $( "#a4" ).slideToggle( "slow", function() {});
            if ($(this).hasClass('on')){
                    $(this).removeClass('on');
            }else{
                $(this).addClass('on');
            }
        });
    });
HTML:


xyz
xyz
xyz
xyz

因为所有处理程序看起来都一样,所以可以创建一个返回函数的函数:

函数createHandler(选择器){
返回函数(){
$(选择器).slideToggle(“slow”,function(){});
if($(this).hasClass('on')){
$(this.removeClass('on');
}否则{
$(this.addClass('on');
}
}
}
然后像这样使用它:

$(“#q1”)。单击(createHandler(“#a1”))
要了解更多有关此原理的信息,请搜索“高阶函数”和“闭包”


因为所有的#q1,#q2。。。如果您在单击时也在做同样的事情,那么您可以利用这些类来完成此操作,并且使用
您可以在单击时参考q类的id。此外,您还可以定义#q1或q类的初始状态,因为只有两个状态有类“开”或没有,因此可以直接在HTML中定义默认状态,而不是在JS中进行检查。比如:

考虑到您的HTML结构,我能想到的最简单的方法是:

$(document).ready(function() {

  // selecting all the elements you need to work with,
  // and binding the anonymous function of the click()
  // method as the event-handler:
  $("#q1, #q2").click(function() {

    // here $(this) will refer to the element that fired the
    // click event, from that element:
    $(this)
      // we navigate to the next-sibling element matching the
      // supplied selector:
      .next('.answers')
      // we use the slideToggle() method to show/hide the element,
      // using an Arrow function to compose the anonymous
      // function so that we can use the same this (and therefore
      // $(this)) as the outer function:
      .slideToggle('slow', () => {

        // here $(this) still refers to the clicked element, as
        // Arrow functions don't establish their own 'this'; and
        // we use the toggleClass() method to add, or remove, the
        // supplied class based on whether it already exists on
        // the element:
        $(this).toggleClass('on');
    });

  // here we again call the click() method, without arguments, in
  // order to fire the click event on page-load (which, in this
  // context will cause the answers to be hidden on page-load):
  }).click();
});
$(文档).ready(函数(){
$(“#q1,#q2”)。单击(函数(){
$(this).next('.answers').slideToggle('slow',()=>{
$(this.toggleClass('on');
});
})。单击();
});
*,
::之前,
::之后{
框大小:边框框;
保证金:0;
填充:0;
}
.faq_框{
边框:1px实心#000;
保证金:0.2米自动;
宽度:80vw;
}
.问题{
背景色:#ffff;
边框:1px实心透明;
边框底色:#000;
光标:指针;
字体大小:1.2米;
字体大小:粗体;
过渡:背景色0.3s线性;
}
.问题::之前{
内容:属性(id)“:”;
文本转换:大写;
}
.答案::之前{
内容:属性(id)“:”;
}
.在{
背景色:#0f06;
}

xyz
xyz
xyz
xyz

您好,如果您的代码能够正常工作,并且您希望使其更高效,那么您可能需要继续询问;如果您在运行此代码时遇到错误,那么这将是本文的主题,但您需要解释您遇到的错误。我还对你尝试过的“逗号分隔的东西”感兴趣,它做了什么,它到底是如何打破的?您是否能够分享足够的“”代码,以便我们重现您的问题?@davidsaysrestatemonica我的代码正常工作,如果不是合适的地方,请道歉。。我提到的是:$(“$(q1,#q2,#q3,#q4”)。单击(函数(){$(“#a1”).slideToggle();如果($(this.hasClass('on')){$(this.removeClass('on');}其他{$(this.addClass('on');});没有真正的问题,这两个社区之间似乎存在重叠(尽管我没有参与其中)。关于你的代码,你能把它编辑成你的问题,并解释它是如何失败或不起作用的吗?此外,请发布与您的问题相关的HTML和CSS。为了编辑您的问题,您的问题标签下方有一个链接,或者您可以使用此评论中的链接。@DavidSaysRestatemonica在Kai的帮助下,我的问题几乎解决了。但我可能仍然应该编辑这个问题,以便对其他人有用,也许有人知道更好的解决方案。谢谢你们的帮助。我将等待一点,接受作为答案。虽然我认为#a1,2,3,4是另一个div,但有了这个帮助,我也许可以让它工作。我可能会做一个div。谢谢你,我将用这些做实验,明天返回结果。这正是我想要的,谢谢!是的,这是最简单最短的一个!我没想到我的代码是7行:)。非常感谢。最后一次点击根本不需要,因为我已经用css隐藏了答案。我很高兴能提供帮助,并衷心感谢您的称赞!至于你希望在将来找到更短的解决方案,你会的。只要你练习,关注博客或YouTube教程,在这里提问或回答问题,这就是所需的全部:练习。祝你好运!
$(document).ready(function(){

    var qClasses = $('.q');
    
    qClasses.on('click', function(){
        var $this = $(this);
        var aIds =  $this.data('id');

        $(aIds).slideToggle("slow");

        $this.toggleClass("on");
    });

});
$(document).ready(function() {

  // selecting all the elements you need to work with,
  // and binding the anonymous function of the click()
  // method as the event-handler:
  $("#q1, #q2").click(function() {

    // here $(this) will refer to the element that fired the
    // click event, from that element:
    $(this)
      // we navigate to the next-sibling element matching the
      // supplied selector:
      .next('.answers')
      // we use the slideToggle() method to show/hide the element,
      // using an Arrow function to compose the anonymous
      // function so that we can use the same this (and therefore
      // $(this)) as the outer function:
      .slideToggle('slow', () => {

        // here $(this) still refers to the clicked element, as
        // Arrow functions don't establish their own 'this'; and
        // we use the toggleClass() method to add, or remove, the
        // supplied class based on whether it already exists on
        // the element:
        $(this).toggleClass('on');
    });

  // here we again call the click() method, without arguments, in
  // order to fire the click event on page-load (which, in this
  // context will cause the answers to be hidden on page-load):
  }).click();
});